Reputation: 47
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!
Upvotes: 1
Views: 594
Reputation: 78975
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);
}
}
Upvotes: 1
Reputation: 327
Try this.
File file = new File("/my/location");
String contents = new Scanner(file).useDelimiter("\\Z").next();
Happy learning :)
Upvotes: 0
Reputation: 2440
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
}
Upvotes: 0
Reputation: 13571
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
Upvotes: 0