[英]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. 我正在从getResourceAsStream读取资源,将所有文本添加到StringBuilder并将内容写入新文件。 However, the text comes back without newlines.
但是,文本返回时没有换行符。 When i do the same, but read a file without getResourceAsStream, it works perfectly.
当我做同样的事情,但读取没有getResourceAsStream的文件时,它可以完美地工作。
The code looks like the following: 该代码如下所示:
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();
If you are using a BufferedReader.readLine() it reads everything upto the new line char. 如果您使用的是BufferedReader.readLine(),它将读取所有内容,直到新行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.
就像在换行符上标记一样..至于BufferedReader.read(),我不太确定为什么要跳过新行。 The jdk source has something like this:
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++];
}
}
}
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...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.