确定文件是否以 EOF 字符正确结束
Determining wheter a file ends properly with an EOF character
我正在处理由 EOF 字符未正确终止的文件引起的问题。
如何检测文件是否包含正确的 EOF,如果 Java / Scala 中不存在,如何正确地 添加它?
I am dealing with problems caused by files that aren't properly terminated by an EOF character.
实际上,我怀疑那是真的。在我的脑海中,我想不出有任何主流操作系统需要终止带有 EOF 字符的文件。 (This article 解释了 "EOF character" 的神话,以及为什么 ^Z 或 ^D 都不是 EOF 字符。是的,一些 shell 在读取用户输入时将一个或另一个解释为 EOF "markers"通过控制台流式传输,但这是一种特殊情况......您的应用程序在读取流时肯定不会看到 ^Z 或 ^D。)
您可能已将应用程序编码为预期 某种 EOF 字符。如果有,那么最好的解决方案可能是修复应用程序。 (我想不出一个好的理由来设计一个应用程序以这种方式工作......)
也有可能你真正的问题是别的。例如,您的文件的最后一行可能没有以可识别的行尾序列结尾。这肯定会导致某些经典 Linux / Unix 实用程序出现问题。
为了完整起见,这里是对您提出的问题的回答。
How can I detect whether a file contains a proper EOF, and properly add it if it is not present in Java / Scala?
判断文件是否未以特定字符(例如 ^Z)结尾的方法是简单地读取文件的最后一个字符,并对其进行测试。例如,在 Java(未测试)中:
import java.io.*;
public class TestForArcaneEOF {
public static void main(String[] args) throws IOException {
Reader reader;
if (args.length == 0) {
reader = new InputStreamReader(System.in);
} else {
reader = new FileReader(args[0]);
}
reader = new BufferedReader(reader);
int last = 0;
int ch;
while ((ch = reader.read()) != -1) {
last = ch;
}
if (last == 0x1a) {
System.out.println("Ends with ^Z");
} else {
System.out.println("Doesn't end with ^Z");
}
}
}
在文件末尾添加一个字符(例如^Z)更简单:
- 以 "append" 模式打开文件。
- 写字符。
- 关闭文件。
我正在处理由 EOF 字符未正确终止的文件引起的问题。
如何检测文件是否包含正确的 EOF,如果 Java / Scala 中不存在,如何正确地 添加它?
I am dealing with problems caused by files that aren't properly terminated by an EOF character.
实际上,我怀疑那是真的。在我的脑海中,我想不出有任何主流操作系统需要终止带有 EOF 字符的文件。 (This article 解释了 "EOF character" 的神话,以及为什么 ^Z 或 ^D 都不是 EOF 字符。是的,一些 shell 在读取用户输入时将一个或另一个解释为 EOF "markers"通过控制台流式传输,但这是一种特殊情况......您的应用程序在读取流时肯定不会看到 ^Z 或 ^D。)
您可能已将应用程序编码为预期 某种 EOF 字符。如果有,那么最好的解决方案可能是修复应用程序。 (我想不出一个好的理由来设计一个应用程序以这种方式工作......)
也有可能你真正的问题是别的。例如,您的文件的最后一行可能没有以可识别的行尾序列结尾。这肯定会导致某些经典 Linux / Unix 实用程序出现问题。
为了完整起见,这里是对您提出的问题的回答。
How can I detect whether a file contains a proper EOF, and properly add it if it is not present in Java / Scala?
判断文件是否未以特定字符(例如 ^Z)结尾的方法是简单地读取文件的最后一个字符,并对其进行测试。例如,在 Java(未测试)中:
import java.io.*;
public class TestForArcaneEOF {
public static void main(String[] args) throws IOException {
Reader reader;
if (args.length == 0) {
reader = new InputStreamReader(System.in);
} else {
reader = new FileReader(args[0]);
}
reader = new BufferedReader(reader);
int last = 0;
int ch;
while ((ch = reader.read()) != -1) {
last = ch;
}
if (last == 0x1a) {
System.out.println("Ends with ^Z");
} else {
System.out.println("Doesn't end with ^Z");
}
}
}
在文件末尾添加一个字符(例如^Z)更简单:
- 以 "append" 模式打开文件。
- 写字符。
- 关闭文件。