我正在从getResourceAsStream读取资源,将所有文本添加到StringBuilder并将内容写入新文件。但是,文本没有换行。 当我这样做,但是在没有getResourceAsStream的情况下读取文件时,它可以很好地工作。
代码如下所示:
InputStream styleFile = this.getClass().getResourceAsStream(
"/path/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();
答案 0 :(得分:2)
如果您使用的是BufferedReader.readLine(),它会读取新行char的所有内容。新行字符不会附加到您获得的字符的末尾。它就像在新行字符上标记一样..对于BufferedReader.read()我不太清楚为什么新行被跳过。 jdk源代码如下:
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++];
}
}
}
无论如何你的情况..编写一个输出新行的程序很简单......
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...