Java Formatter class toString() doesn't work - java

I'm going through a Java book and now onto Formatter class outputting into a text file. I added in an extra line of code to test for the toString() towards the end of addRecords() but it does't work. Why is it so?
Furthermore, I am a bit confused about the closeFile() at if (output != null) then close the file. From my understanding is that I thought output has already formatted all the input into the text file how about it's still not null which leads me to try out the toString() at addRecords().
Thanks in advance!
// Fig. 15.3: CreateTextFile.java
// Writing data to a sequential text file with class Formatter.
import java.io.FileNotFoundException;
import java.lang.SecurityException;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class CreateTextFile
{
private static Formatter output; // outputs text to a file
public static void main(String[] args)
{
openFile();
addRecords();
closeFile();
}
// open file clients.txt
public static void openFile()
{
try
{
output = new Formatter("clients.text"); // open the file
}
catch (SecurityException securityException)
{
System.err.println("Write permission denied. Terminating.");
System.exit(1); // terminate the program
}
catch (FileNotFoundException fileNotFoundException)
{
System.err.println("Error opening file. Terminating.");
System.exit(1); // terminate the program
}
}
// add records to file
public static void addRecords()
{
Scanner input = new Scanner(System.in);
System.out.printf("%s%n%s%n? ",
"Enter account number, first name, last name and balance.",
"Enter end-of-file indicator to end input.");
while (input.hasNext()) // loop until end-of-file indicator
{
try
{
// output new record to file; assumes valid input
output.format("%d %s %s %.2f%n", input.nextInt(),
input.next(), input.next(), input.nextDouble());
}
catch (FormatterClosedException formatterClosedException)
{
System.err.println("Error writing to file. Terminating.");
break;
}
catch (NoSuchElementException elementException)
{
System.err.println("Invalid input. Please try again.");
input.nextLine(); // discard input so user can try again
}
System.out.println(output.toString());
System.out.print("? ");
} // end while
} // end method addRecords
// close file
public static void closeFile()
{
if (output != null)
output.close();
}
} // end class CreateTextFile
Here's the command line output:
Enter account number, first name, last name and balance.
Enter end-of-file indicator to end input.
? 100 Bob Blue 24.98
java.io.BufferedWriter#55f96302

I added in an extra line of code to test for the toString() towards the end of addRecords() but it doesn't work. Why is it so?
It is working. But it is not doing what you apparently think it does / should do.
The javadoc for Formatter.toString() says:
"Returns the result of invoking toString() on the destination for the output."
In this case, you have created a Formatter that writes to a BufferedWriter. When Formatter.toString() calls toString() on a BufferedWriter, it doesn't give you back the stuff that you wrote to the file. Rather, it returns you what Object.toString() would return. That is described here.
If you want your Java application print out what has been written to the file, you will need to open it, read it and copy the content to System.out. And before you do that, you will need to flush() or close() the Formatter.
A simpler idea would be to look at the file using a text editor or the less command, or similar ... after the application has completed. If the file is empty or shorter than you expect, make sure that your application always closes the Formatter before terminating.

BufferedWriter uses the default toString() implementation from Object. The returned String contains the class name and the Objects hashCode().
If you want a string containing the output either use String.format or a StringWriter to format your output before you write it to the file.
Edit: as mentioned by other answers the BufferedWriter is used internally by the Formatter when it is created with a filename. Formatter.toString() calls BufferedWriter.toString() in this case.

Related

How to print multiple exceptions in an input file to an errors file?

I'm in a computer science (java) class right now and our task is to create a program that reads integers from an input.txt file (the professor will have this) and prints out all the integers into an output.txt file. Any exceptions/errors will need to be printed to an errors.txt file that our program creates. (We are learning about Exceptions in class now).
My program is able to read from an input file and print out just the integers to an output.txt, but I'm having problems printing out all the exceptions that might occur. For example, if the input file has "abc" as one of the lines, it should print out a message in the errors.txt file saying that it isn't an integer.
What happens with my program is that as soon as one exception is thrown, it doesn't keep going to print out all the other exceptions even if there are more to print. It just stops at that point.
So for example, something like this:
try{
while (fileScan.hasNext())
{
num = fileScan.nextInt();
}
}catch(Exception e)
{
erout.println(e); //prints the error to the file.
fileScan.nextLine();
}
erout is my PrintWriter object for the error.txt file. fileScan for the input.txt.
I'm just not sure how to get it to go through all of the input.txt file and keep track of all the exceptions it will throw, then print all those to an error.txt file. Any help would be appreciated, thanks. :)
You could move the while loop outside of the try statement.
while (fileScan.hasNext())
{
try{
num = fileScan.nextInt();
}catch(Exception e)
{
erout.println(e); //prints the error to the file.
fileScan.nextLine();
}
}
You need to re-order your while and try/catch:
List<Exception> exceptions = new ArrayList<>();
while (fileScan.hasNext()) {
try {
num = fileScan.nextInt();
// more code here to process num
} catch (Exception e) {
// Might also want to create a custom exception type to track
// The line/file that the error occurred upon.
exceptions.add(e);
fileScan.nextLine();
}
}
All you gotta do is move the try/catch within the while:
while (fileScan.hasNext())
{
try {
num = fileScan.nextInt();
}
catch (Exception e) {
erout.println(e); //prints the error to the file.
fileScan.nextLine();
}
}

Writing to files and I/O

I'm trying to write a program that gets a users input that is then written to an output file called userStrings.txt. I'm also trying to stop the processing once the user inputs 'done', but I'm not sure how to accomplish this.
Here is my code:
import java.io.*;
import java.util.Scanner;
public class Murray_A04Q2 {
public static void main(String[] args) throws IOException {
// Name of the file
String fileName = "userStrings.txt";
Scanner scan = new Scanner(System.in);
try {
// FileReader reading the text files in the default encoding.
FileWriter fileWriter = new FileWriter("userStrings.txt");
// Wrapping FileReader in BufferedReader.
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("A string");
bufferedWriter.write("Another string");
bufferedWriter.write("Yet more text...");
System.out.println("Enter something, DONE to quit: ");
String input = scan.nextLine();
// Closing file
bufferedWriter.close();
}
catch (IOException ex){
System.out.println("Error writing to file " + "userStrings.txt" + "");
}
} // End of method header
} // End of class header
In order to write to a file, do I still use System.out.println? and is the bufferedWriter.write even necessary? I'm just trying to understand the I/O and writing to files better.
Thanks!
In order to write to a file, do I still use System.out.println?
No. That writes to standard output, not to your file.
If you are using println then you need to wrap your BufferedWriter with a PrintWriter. (Look at the javadocs for the System class where the out field is documented.)
and is the bufferedWriter.write even necessary?
If you are going to write directly to the BufferedWriter then yes, it is necessary, though you probably need to an appropriate "end of line" sequence. And that's where it gets a bit messy because different platforms have different native "end of line" sequences. (If you use PrintWriter, the println method picks the right one to use for the execution platform.)
I'm also trying to stop the processing once the user inputs 'done', but I'm not sure how to accomplish this.
Hint: read about the Scanner class and System.in.
Right under you take input from the console, run a while loop to test that input is not equal to "done". Inside the while loop, add input to your file and get the next line of input.
while(!input.toLowerCase().Equals("done"))
{
bufferedWriter.write(input);
input = scan.nextLine();
}

File writing in java [duplicate]

This question already has answers here:
How do I create a file and write to it?
(35 answers)
Closed 8 years ago.
I've just started on my college journey ( 'Yay' ). I'm also new to the site so feel free to lecture me on things I may have done wrong as far as asking questions is concerned.
I was given a project, which has already been graded and all, and the program should ==>> first read lines of standard input (Input file name using keyboard) and for each line of input, if the user enters exit, the application terminates; otherwise, the application interprets the line as a name of a text file. The application creates or recreates this file and writes to it two lines of output, the name of the file and the current date and time. The application then closes the file, reopens it for reading, and writes its contents to standard output. The application writes to standard output the name of the file enclosed by square brackets. After writing the file name,
the application writes the contents of the file with each line prefixed by its corresponding line
number, a full colon, and a space.
I have worded it just as my professor did, so I apologize for any unclear statements. Here's what I got for it:
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.io.File;
import java.io.ObjectInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
public class Project1
{
public static void main() throws IOException
{
String input = "";
while(!sc.equals("exit"))
{
System.out.println("Enter file here!\n Type 'exit' to terminate");
Scanner sc = new Scanner(System.in);
input = sc.nextLine();
try
{
File file = new File (input,".txt"); // Creates pointer to a file.
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
file.createNewFile();
file.getAbsolutePath();
printFileAndDate(file);
}
catch(IOException e)
{
System.out.print("Something wrong :(");
e.printStackTrace();
}
}
System.exit(0);
}
static void printFileAndDate(File temp)
{
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println("[ " + temp.getPath() + " ]");
System.out.println(dateFormat.format(cal.getTime()));
}
}
What I attempted to do there was the following:
-Get User Input => Save Input as a file => Call method "printFileAndDate" and print the file along with the current date and time in the correct format.
However, whenever I run it, it always gives me an exception error, which means the file was never really created or that it isn't able to find it.
The list of ISSUEs, I could find :
First, your main method signature is totally wrong
public static void main() throws IOException
change to
public static void main(String[] args) throws IOException
Second, it is not a good practice to throws exception inside main method.
The good practice is to use try catch block
Third, you have your Scanner varialbe after the while loop which does not make sense
while(!sc.equals("exit"))
{
System.out.println("Enter file here!\n Type 'exit' to terminate");
Scanner sc = new Scanner(System.in); <-?!!!!!!
change to
System.out.println("Enter file here!\n Type 'exit' to terminate");
Scanner sc = new Scanner(System.in);
while(!sc.equals("exit"))
{
Fourth , you define File variable this way
File file = new File (input,".txt"); <-- totally wrong
change to
File file = new File ("input.txt"); <-- if you use relative path
Fifth there is not need for System.exit(0);at the end of main method

Writing Multiple Lines To A File At Different Times

I have the basics of my program finished.
The idea is that the user can specify a shape color width height etc. Upon inputting the data, constructors are called which create output, or there are other options which create output that the user can specify.
My goal is to get all of this output into a text file.
Currently I create a scanner for reading:
static Scanner input = new Scanner(System.in);
Then in my main driver method I create a Formatter:
public static void main(String[] args) {
Formatter output = null;
try{
output = new Formatter("output.txt");
}
catch(SecurityException e1){
System.err.println("You don't have" +
" write accress to this file");
System.exit(1);
}
catch(FileNotFoundException e){
System.err.println("Error opening or" +
" creating file.");
System.exit(1);
}
After each time I expect output I have placed this bit of code:
output.format("%s", input.nextLine());
And finally I close the file with
output.close()
The file is created but it is currently blank. I know I'm on the right track, because I've tried doing this:
output.format("%d", i);
where i is an integer of 0 and the file writes correctly.
However, I cannot seem to get it to work for an entire line, or for the output at all.
Please help!
I am not an expert but why can you not just use "FileWriter"?
Is it because you want to catch those exceptions to display useful information to the user?
Or have I misunderstood the question completely? - If so, sorry and just disregard this.
import java.io.FileWriter;
import java.io.IOException;
try
{
FileWriter fout = new FileWriter("output.txt"); // ("output.txt", true) for appending
fout.write(msg); // Assuming msg is already defined
fout.close();
}
catch (IOException e)
{
e.printStackTrace();
}

How do I print to the file?

I am working through an assignment and have run into a few snags.
My program prints output to the screen, (not how I need it yet) but only prints the first entry to the file. Below is a snippet of the code. The file appears to be reading in the data from the input file, but the loop does not output to the file past the first entry.
Scanner in = new Scanner(System.in); //Scanner object to read input from the file
System.out.println("Enter filename to read "); //file name prompt
String inputFileName = in.nextLine(); //line input reads next line
/*
* TODO 2) Use an unbuffered file input stream to open listings.txt file
* and read in property listings.
*/
Scanner reader = null;
try {
reader = new Scanner(new File(inputFileName));
} catch (FileNotFoundException e) {
System.out.println("Try Again"); //error window if name is null
JOptionPane.showMessageDialog(null, "You must enter a filename", "File input error", JOptionPane.ERROR_MESSAGE);
return;
}
PrintWriter out = new PrintWriter("agentreport.txt"); //This method prints out the file readfile.txt a word at a time
while (reader.hasNextLine()) { //It needs to output to the text file. Currently a file is created, but it is empty?
Scanner s2 = new Scanner(reader.next());
#SuppressWarnings("unused")
boolean b;
while (b = s2.hasNext()) {
String output = s2.next();
String output2 = output.toUpperCase(); //converts output to upper case
System.out.println(output2);
out.print(output2); //only printing the first entry to the agentsreport.txt file. Not stepping thru the file for some reason?
}
Even if you are using automatic flushing, which you aren't in this case, the PrintWriter object would output anything in its internal buffer unless you do one of two things:
1) Use the println(), printf(), or format() to methods
2) Make a call to the flush() method every time you print, this way all of the data in the internal buffer gets written out.
Note: The print() method does not cause the PrintWriter object to flush() its buffer.
try adding a call to flush() after you call print()
Example of split()
PrintWriter out = new PrintWriter("agentreport.txt");
while (reader.hasNextLine()) {
String words = reader.nextLine().split();
#SuppressWarnings("unused")
boolean b;
for(String word : words) {
String output = word ;
String output2 = output.toUpperCase(); //converts output to upper case
System.out.println(output2);
out.print(output2);
}
One thing that immediately jumps out is that you aren't handling your resources properly.
Any time you use an IO resource such as a reader/database connection/etc., you should always close it using a finally block, using this sort of pattern:
Reader reader = /* construct it however */
try {
/* do something with the reader */
}
finally {
reader.close();
}
If you don't do this, there's no guarantee that the reader will actually be closed, and your application will leak file descriptors/connection pool connections/etc., until eventually it won't be able to get hold of any more and your app crashes. (This won't always have fatal consequences, but it's such a straightforward pattern you should use it every time until it becomes automatic).
In this case, you aren't closing your writer at all, which means that it's not guaranteed that it ever actually flushes its output to the file. It would be perfectly in accordance with the Writer interface for it to write everything or nothing - without the flush, you have no guarantees. Note that closing the writer will automatically call flush, so that's the best bet once you're done with it.
So the latter part of your code should look like:
PrintWriter out = new PrintWriter("agentreport.txt");
try {
// Existing code here
}
finally {
// This closes the file and frees the descriptor, but also flushes the buffers
out.close();
}
Also, how are you handling the IOExceptions that can be thrown by the reading and writing? Are you catching them and swallowing them somewhere? If so, it's possible that your code is throwing an exception telling you exactly why it can't write, and you're just ignoring it and then looking puzzled.
Not to put too fine a point on it, error handling is probably the most significant part of good software development. It's not too hard to write software that works when everything's fine; the most challenging part is handling things well when you run out of space on the hard drive, or the network is temporarily down, etc.
In this case the most pragmatic approach would be to just let the exception be thrown out of the top of your main method. In this case your application will "crash", and you'll get a stacktrace + error message on the console, which will make it immediately clear that something went wrong, and give you a very good idea of what it was.
try
out.println(output2);
http://docs.oracle.com/javase/6/docs/api/java/io/PrintWriter.html
also I'd use a var other than "out" as when system.out is imported to use the shortcode 'out.println()', this could cause variable confusion
edit: good point #Hunter McMillen, changed to println as append is for a CharSequence.
try (
Scanner reader = new Scanner(new File(inputFileName));
PrintWriter writer = new PrintWriter(new FileOutputStream("agentreport.txt"), true);
) {
while (reader.hasNextLine()) {
String output = reader.nextLine().toUpperCase();
System.out.println(output);
writer.println(output);
}
} catch (FileNotFoundException e) {
System.out.println("Try Again"); //error window if name is null
JOptionPane.showMessageDialog(null, "You must enter a filename", "File input error", JOptionPane.ERROR_MESSAGE);
}

Categories