In C++ if I wish to read input till the EOF I can do it in the following manner
while(scanf("%d",&n))
{
A[i]=n;
i++;
}
I can then run this code as ./a.out < input.txt. What is the java equivalent of this code?
The readUtf8Line() method reads the data until the next line delimiter – either \n , \r\n , or the end of the file. It returns that data as a string, omitting the delimiter at the end. When it encounters empty lines, the method will return an empty string. If there isn't no more data to read, it will return null .
You need to make a counter and make a boolean variable. if counter exceeds the number of test cases read, then make the boolen true. and in while loop you need to give the boolean while(boolean_value); as soon as all test cases are read and you make boolean true, while loop will exit.
Signals that an end of file or end of stream has been reached unexpectedly during input. This exception is mainly used by data input streams to signal end of stream.
To read the line and move on, we should use the nextLine() method. This method advances the scanner past the current line and returns the input that wasn't reached initially. This method returns the rest of the current line, excluding any line separator at the end of the line.
Here is Java equivalent code using BufferedReader and FileReader classes.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class SmallFileReader {
public static void main(String[] args) throws IOException {
Option 1:String fileName = args[0];
BufferedReader br = new BufferedReader(new FileReader(fileName));
Option 2:BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a file name: ");
String fileName = br.readLine();
//BufferedReader br = new BufferedReader(new FileReader("Demo.txt"));
String line=null;
while( (line=br.readLine()) != null) {
System.out.println(line);
}
}
}
I made little modification to @Vallabh Code.
@tom You can use the first option, if you want to input the file name through command line.java SmallFileReader Hello.txt
Option 2 will ask you the file name when you run the file.
You can do this:
Scanner s = new Scanner(System.in);
while (s.hasNextInt()) {
A[i] = s.nextInt();
i++;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With