gpt4 book ai didi

java - 从文本文件读取时如何维护 EOL 字符?

转载 作者:行者123 更新时间:2023-12-01 21:34:23 24 4
gpt4 key购买 nike

BufferedReader.readLine() 会自动删除 EOL 字符,我不能简单地执行 readLine(),然后在其末尾添加“\r”。我试过了

InputStream myFile = new FileInputStream("C:\\test.txt");
StringBuilder sb = new StringBuilder();

int i;

while((i = myFile.read()) != -1)
{
char ch = (char) i;
sb.append(ch);
}

System.out.println(sb);

但是“char ch = (char) i”会丢失字节数据,因为 int 为 4 个字节,而 char 为 2 个字节。

我再说一遍,我不能做这样的事情

sb.append(ch+"\r");

因为此通用代码将读取的某些文件将包含 CR,而其他文件则不会。

从 java.nio.* 中,Files.readAllBytes(Path path) 似乎是一个选项。但我对它不熟悉,无法判断它是否返回 EOL 字符或不基于 Javadoc

最佳答案

理想情况下,您不要触及字节。例如

public static String fromFile(File file, Charset charset) throws IOException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset))) {
StringWriter out = new StringWriter();
char[] cbuf = new char[8192];
int read;
while ((read = reader.read(cbuf)) != -1) {
out.write(cbuf, 0, read);
}
return out.toString();
}
}

将所有内容直接转换为单个字符串。将 byte 转换为 char 确实很危险,您不应该尝试自己这样做,除非您知道它只是 ascii。让内置字符集来做这件事。使用正确的方法已经够棘手的了。

Files.readAllBytes() 确实返回 EOL 字符,因为它处理字节,并且不会尝试解释这些字节的含义。

public static String fromPath(Path path, Charset charset) throws IOException {
byte[] bytes = Files.readAllBytes(path);
return new String(bytes, 0, bytes.length, charset);
}

相当于使用 nio 方法。使用 Paths.get("myfile.txt") 调用,而不是使用 new File("myfile.txt")

关于java - 从文本文件读取时如何维护 EOL 字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37079283/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com