简体   繁体   中英

only printing the string present on the first line of the text in java

I am new to java and want to print the string present in the text file character by character but its only printing the first line string and when I write something on the next line in the text file the code is not printing them. Can someone help me in this. I am attaching the code below!

import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;

public class main {
    
    public static void main(String[] args) throws FileNotFoundException {
        char ch;
        
        File newFile = new File("C:/temp/sourcecode.txt");
        Scanner scanFile = new Scanner(newFile);
        
        String str;
        str = scanFile.nextLine();
        int l = str.length();
        for(int i =0; i<l ; i++) {
            ch = str.charAt(i);
            System.out.println(ch);
        }
    }
    
}

Thank you in advance!

I am new to java and want to print the string present in the text file character by character but its only printing the first line string

It's because you are reading only the first line. Moreover, you are reading the line without checking if there is any line in the file or not and therefore you will get an exception if your file is empty. You must always check, if scanFile.hasNextLine() before calling scanFile.nextLine() to read a line from the file.

In order to repeat the process for each line, you need a loop and most natural loop for this requirement will be while loop. So, all you need to do is to put the following code:

String str;
str = scanFile.nextLine();
int l = str.length();
for (int i = 0; i < l; i++) {
    ch = str.charAt(i);
    System.out.println(ch);
}

into a while loop block as shown below:

while (scanFile.hasNextLine()) {
    String str;
    str = scanFile.nextLine();
    int l = str.length();
    for (int i = 0; i < l; i++) {
        ch = str.charAt(i);
        System.out.println(ch);
    }
}

You will want to work with the scanner (not the string retuned from nextLine(). If you look carefully you are reading your file once. Your loop should look something like this:

while(scanFile.hasNextLine()){
  String line = scanFile.nextLine();
}

JavaDoc API on hasNextLine

It happens because nextLine() reads a file until Scanner.LINE_PATTERN ( \\r\\n in your case). To read the whole file:


while (scanFile.hasNextLine()){
  str = scanFile.nextLine();
  //your code here

 }

Try this.

File file = new File("/my/location");
String contents = new Scanner(file).useDelimiter("\\Z").next();

Happy learning :)

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