我试着按照下面的例子Found it here Java: Find if the last line of a file is empty来确定一个文件是否以CRLF(空行)结束,但是当我向方法传递一个字符串时,RandomAccessFile会说没有找到文件。问题是我不能给它提供文件路径,但我有一个字符串形式的文件内容,所以我尝试使用file f= new file (MyString)创建一个文件;然后将创建的文件传递给方法,但它不起作用,它给我同样的错误(文件找不到)(它认为文件的第一行作为路径)!
我如何从我的字符串中创建一个被RandomAccessFile接受的文件,该字符串包含我想要检查的文件的内容,如果它完成的话。
希望我说得够清楚了。
public static boolean lastLineisCRLF(String filename) {
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(filename, "r");
long pos = raf.length() - 2;
if (pos < 0) return false; // too short
raf.seek(pos);
return raf.read() == '\r' && raf.read() == '\n';
} catch (IOException e) {
return false;
} finally {
if (raf != null) try {
raf.close();
} catch (IOException ignored) {
}
}
}发布于 2013-07-10 00:58:53
如果您已经将文件内容作为字符串存储在内存中,则不需要再次将其写入文件来确定最后一行是否为空。只需用行尾字符拆分内容,然后从最后一行裁剪空格,看看是否还剩下什么:
String fileContent = "line1\nline2\nline3\nline4\n";
// -1 limit tells split to keep empty fields
String[] fileLines = fileContent.split("\n", -1);
String lastLine = fileLines[fileLines.length - 1];
boolean lastLineIsEmpty = false;
if(lastLine.trim().isEmpty())
{
lastLineIsEmpty = true;
}
//prints true, line4 followed by carriage return but
//no line 5
System.out.println("lastLineEmpty: " + lastLineIsEmpty);https://stackoverflow.com/questions/17553774
复制相似问题