1

Read data from the file and return the same data in a string It only returns the last line, how can I return the same data in the file?

File


    This is test file.
    This is test file!
    Test
    test file
    
    
    
    
    xxas   test
    
    fil
    
    !  test
    
    te

   import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    
    public class Read {
        static String input = "";
    public static void main (String [] args) throws FileNotFoundException {
            Scanner file = new Scanner(new File("Example.txt"));
            while(file.hasNextLine()){
                input = file.nextLine();
            }
            System.out.println(input);
    
    }
    }
Jack
  • 103
  • 5

2 Answers2

1

input variable should be a StringBuilder and use append:

Scanner file = new Scanner(new File("Example.txt"));
            while(file.hasNextLine()){
                input.append(file.nextLine());
            }
            System.out.println(input.toString());
rownski
  • 11
  • 2
  • If I want to clear the StringBuilder, how can I do that? I tried setLength(0) but it's not working. – Jack Jul 29 '20 at 10:13
  • If setting setLenght(0) doesn't work try the second option in this thread: https://stackoverflow.com/questions/5192512/how-can-i-clear-or-empty-a-stringbuilder – rownski Jul 30 '20 at 13:23
0

You can simply append each line to 'input':

input += file.nextLine() + "\n";

And performance wise it might be better to declare 'input' as a StringBuilder

Another option is to insert System.out.println(input); into the while loop

Uri Loya
  • 1,181
  • 2
  • 13
  • 34