Running this program shows the wrong output. My file "values.txt" contains 45678
and the output
after running the program is 00000
.
import java.util.Scanner;
public class array{
public static void main(String[] args)throws IOException
{
final int SIZE = 6;
int[] numbers = new int[SIZE];
int index = 0;
File fl = new File("values.txt");
Scanner ab = new Scanner(fl);
while(ab.hasNext() && index < numbers.length)
{
numbers[index] = ab.nextInt();
index++;
System.out.println(numbers[index]);
}
ab.close();
}
}
Instantiate a PrintStream class by passing the above created File object as a parameter. Invoke the out() method of the System class, pass the PrintStream object to it. Finally, print data using the println() method, and it will be redirected to the file represented by the File object created in the first step.
Java Read File line by line using BufferedReader We can use java. io. BufferedReader readLine() method to read file line by line to String. This method returns null when end of file is reached.
You can use BufferedReader to read large files line by line. If you want to read a file that has its content separated by a delimiter, use the Scanner class. Also you can use Java NIO Files class to read both small and large files.
You can't open the same file to read and write at the same time. You have to open and save the file information in a data structure and then close it. Then you have to work with the data structure in memory and open the file to write results. And when you finish to write you should close it.
You first assign to numbers[index]
then increase index
and output numbers[index]
(for the next empty value).
Swap index++
and System.out
calls.
Move index++
to after the System.out.println
call.
At the moment you're always outputting an unassigned value of numbers
. (In Java every element in an array of int
is initialised to zero).
An alternative would be to discard index++;
entirely and write System.out.println(numbers[index++]);
. I personally find that clearer.
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