我有下面的 readfile() java 函数来读取 .htm 文件
private String readfile(String inputDoc) throws IOException {
FileInputStream fis = null;
InputStreamReader isr = null;
String text = null;
//open input stream to file
fis = new FileInputStream(inputDoc);
isr = new InputStreamReader(fis, "UTF-8");
StringBuffer buffer = new StringBuffer();
int c;
while( (c = isr.read()) != -1 ) {
buffer.append((char)c);
}
text = buffer.toString();
isr.close();
return text;
}
这是输入文档的示例片段
<?xml version="1.0" encoding="utf-8"?><html>
<head>
出于某种原因,从 readfile() 返回的文本字符串是 <?xml version="1.0" encoding="utf-8"?><html>\r\r\n<head>
但我希望它是 <?xml version="1.0" encoding="utf-8"?><html>\r\n<head>
概述here Windows 中的换行符\r\n
我在 Windows 7 上的 IntelliJ Idea 中运行上面的函数。(IDEA 默认编码设置为 UTF-8)
有谁知道为什么我从换行符的 readfile(String inputDoc) 函数得到这个奇怪的结果
最佳答案
当您编写 \n
时,它会在 Windows 上扩展为 \r\n
以实现可移植性。这样,无论您在什么操作系统上运行它,您都可以获得正确的结果而无需额外的代码:\r\n
在 Windows 上,或者只是 \n
在 Unix 上.看起来您正在以二进制模式读取输入(在文本模式下,相同的扩展发生相反:输入中的任何 \r\n
都变成 \n
,所以您不必再担心操作系统),因此您会看到 \r
。然后,当您编写 \n
时,它会扩展为 \r\n
,留下两个 \r
。
关于java - 为什么我在 Windows 中将\r\r\n 作为换行符而不是\r\n 作为换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14059212/