简体   繁体   中英

Trying to get Scanner to scan entire file

String userInput = stdin.nextLine();                        
file = new File(userInput);

Scanner fileScanner = new Scanner(file);    
while(fileScanner.hasNext()) {                  
    fileContents = fileScanner.nextLine();
}

So I'm trying to figure out how I can get my variable fileContents to hold all of the file from the scanner. with the current way I have it setup the variable fileContents is left with only the last line of the .txt file. for what I'm doing I need it to hold the entire text from the file. spaces, chars and all.

I'm sure there is a simple fix to this I'm just very new to java/coding.

You need to change

fileContents += fileScanner.nextLine();  

or

 fileContents  =fileContents + fileScanner.nextLine(); 

With your approach you are reassigning the fileContents value instead you need to concat the next line.

        String userInput = stdin.nextLine();                        
        file = new File(userInput);
        StringBuilder sb = new StringBuilder();

        Scanner fileScanner = new Scanner(file);    
        while(fileScanner.hasNext()) {
            sb.append(fileScanner.nextLine()+"\n");
        }
        System.out.println(sb.toString());

Or follow the @singhakash's answer, because his one is faster performance wise I presume. But I used a StringBuilder to give you an idea that you're 'appending' or in other words, just adding to the data that you wish to use. Where as with your way, you're going to be getting the last line of the text because it keeps overriding the previous data.

You can use below as well:

Scanner sc = new Scanner(new File("C:/abc.txt"));
String fileContents = sc.useDelimiter("\\A").next();

You don't have to use while loop in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM