The file is being created successfully, but I cannot get PrintWriter to print anything to the text file. Code:
import java.io.File;
import java.util.Scanner;
import java.io.IOException;
import java.io.PrintWriter;
public class exams {
public static void main (String[] args) throws IOException{
Scanner scanner = new Scanner(System.in);
System.out.println("How many scores were there?");
int numScores = scanner.nextInt();
int arr[] = new int[numScores];
for (int x=0; x<numScores; x++){
System.out.println("Enter score #" + (x+1));
arr[x] = scanner.nextInt();
}
File file = new File("ExamScores.txt");
if(!file.exists()){
file.createNewFile();
PrintWriter out = new PrintWriter(file);
for (int y=0; y<arr.length; y++){
out.println(arr[y]);
}
}
else {
System.out.println("The file ExamScores.txt already exists.");
}
}
}
The print writer is linked with the file output.PrintWriter output = new PrintWriter("output. txt"); To print the formatted text to the file, we have used the printf() method.
It's most commonly used for writing data to human readable text files or reports. In our first example, we'll use PrintWriter to create a new file by passing in the filename to its constructor as a string. If the file doesn't exists, it will be created.
Class PrintWriter. Prints formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream . It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.
By using PrintWriter than using System. out. println is preferred when we have to print a lot of items as PrintWriter is faster than the other to print data to the console.
You have to flush and / or close the file to get the data written to the disk.
Add out.close()
in your code:
PrintWriter out = new PrintWriter(file);
for (int y=0; y<arr.length; y++){
out.println(arr[y]);
}
out.close()
You need to close the PrintWriter before the program exits which has the effect of flushing the print stream to ensure everything is written to the file. Try this:
PrintWriter out = null;
try {
//...
out = new PrintWriter(file);
//...
} finally {
if (out != null) {
out.close();
}
}
u need to flush and close the file once done writing http://download.oracle.com/javase/1.4.2/docs/api/java/io/PrintWriter.html void close() Close the stream. void flush() Flush the stream.
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