I am trying to follow the below example found it here Java: Find if the last line of a file is empty to determine if a file finish by CRLF(empty line) however when I pass a String to the method RandomAccessFile says file Not Found. the problem is I cant feed it the file path, but I have the contents of the file as a String, so I tried to create a file using File f = new File(myString); and then pass the method the created file but it didnt work and it gave me the same error (File not Found) (it consideres the first line of the file as the path)!

how can I create a file accepted by RandomAccessFile, from my String that contains the contents of the file I want to check if it finishs by CRLF.

Hope I was clear.

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) {
        }
    }
}
有帮助吗?

解决方案

If you have the file contents already in memory as a string, you don't need to write it to a file again to determine if the last line is empty. Just split the contents by an end-of-line character and then trim whitespace off the last line and see if anything is left:

  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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top