1RacerTn
1RacerTn

Reputation: 63

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? 
   }

Upvotes: 2

Views: 277

Answers (4)

Hunter McMillen
Hunter McMillen

Reputation: 61515

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);  
   }

Upvotes: 3

siamii
siamii

Reputation: 24084

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);

}

Upvotes: 0

Andrzej Doyle
Andrzej Doyle

Reputation: 103777

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.

Upvotes: 0

squarephoenix
squarephoenix

Reputation: 1003

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.

Upvotes: 0

Related Questions