0

I am taking a the programming class where we have to compress a file using a Huffman Tree and decompress it.

I am running into a problem where I am unable to capture the last newline character of a txt file. E.G.

This is a line  
This is a secondline
//empty line

So if I compress and decompress the above text in a file, I end up with a file with this

This is a line  
This is a secondline

Right now I'm doing

while(Scanner.hasNextLine()){ 
    char[] cArr = file.nextLine().toCharArray();
    //count amount of times a character appears with a hashmap
    if(file.hasNextLine()){
        //add an occurrence of \n to the hashmap
    }
}

I understand the problem is that the last line technically does not have a "Scanner.hasNextline()" since I just consumed the last '\n' of the file with the nextLine() call.
Upon realizing that I have tried doing useDelimiter("") and Scanner.next() instead of Scanner.nextLine() and both still lead to similar problems.

So is there a way to fix this?
Thanks in advance.

  • 1
    I couldn't think of a way using a Scanner. Try another method for reading files. Here's a good post: http://stackoverflow.com/questions/4716503/reading-a-plain-text-file-in-java – Joe Mar 16 '17 at 19:21

1 Answers1

0

Not to completely change your code or approach, using StringBuilder seems to work well.

File testfile = new File("test.txt");
StringBuilder stringBuffer = new StringBuilder();
try{
    BufferedReader reader =  new BufferedReader(new FileReader(testfile));
    char[] buff = new char[500];
    for (int charsRead; (charsRead = reader.read(buff)) != -1; ) {
        stringBuffer.append(buff, 0, charsRead);
    }
}
catch(Exception e){
    System.out.print(e);
}
System.out.println(stringBuffer);

Checking the total bytes read:

System.out.println(stringBuffer.length()); // 51

List of file size:

ls -l .
51 test.txt

Bytes read match, so it appears it got all lines including the blank line.

note: I use Java 6, modify to suit your version.

Hope this helps.

davedwards
  • 7,011
  • 2
  • 15
  • 45