开发者

reading file from getResourceAsStream omits newline

I'm reading a resource from getResourceAsStream, adding all text to a StringBuilder and writing the content to a new file. However, the text comes back without newlines. When i do the same, but read a file without getResourceAsStream, it works perfectly.

The code looks like the following:

      InputStream styleFile = this.getClass().getResourceAsStream(
            "/pat开发者_运维百科h/path/path/some.css");

    BufferedReader bufRead = new BufferedReader(new InputStreamReader(styleFile));


    StringBuilder builder = new StringBuilder();
    int nextchar;
    while ((nextchar = bufRead.read()) != -1)
    {
       builder.append((char)nextchar);

    }
    FileWriter outFile;
    try
    {
       outFile = new FileWriter(newStyleFile);
    }
   catch (IOException e)
   {
      //Log
   }

   PrintWriter out = new PrintWriter(outFile);
   out.write(builder.toString());
   out.close();


If you are using a BufferedReader.readLine() it reads everything upto the new line char. The new line character is not appended to the end of the chars you obtained. Its like tokenising on the new line character.. as for the BufferedReader.read() I am not too sure why the new line is getting skipped. The jdk source has something like this:

public int read() throws IOException {
synchronized (lock) {
    ensureOpen();
    for (;;) {
    if (nextChar >= nChars) {
        fill();
        if (nextChar >= nChars)
        return -1;
    }
    if (skipLF) {
        skipLF = false;
        if (cb[nextChar] == '\n') {
        nextChar++;
        continue;
        }
    }
    return cb[nextChar++];
    }
}
}

Anyway for your case.. Its simple to write a program that outputs the new line...

BufferedReader br=new BufferedReader(new InputStreamReader(styleFile));
StringBuilder builder = new StringBuilder();
String line=null;
while((line=br.readline())!=null){
    builder.append(line).append("\n");
}

// then write to the new file...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜