I'm trying to write to a file using the printwriter class.

Posted 03 April 2011 - 06:22 AM

Hello, I'm having trouble getting the desired output here. Everything that this program is supposed to do works except that I'm not getting any output to the desired file. I will post the instructions to the problem and then my code. If you need me to give more nfo, just ask. Thanks to anyone for helping me.

Instructions:

Write a program that asks the user for the names of 2 files. The first file should be opened for reading and the second file should be opened for writing. The program should read the contents of the first file, change all characters to uppercase, and store the results in the second file.The second file will be a copy of the first, except that all of the characters will be uppercase. Use notepad or another text editor to create a simple file that can be used to test the program.

my attempt:

import java.io.*;
import javax.swing.*;
import java.util.*;
public class UppercaseFileConverter
{
public static void main(String[] args) throws IOException
{
String fileName = "";
String uppercaseLines = "";
//Get the name of the first file from the user
fileName = JOptionPane.showInputDialog("Please specify the name of the file"
+ " you wish to read from:");
//Create and open the file for reading
File file = new File(fileName);
Scanner inputFile = new Scanner(file);
//While there is another line to read, the program will concatenate
//the line under the uppercaseLine variable in all uppercase
while (inputFile.hasNext())
{
String line = inputFile.nextLine();
uppercaseLines += "\n"+line.toUpperCase();
}
//Get the name of the output file from the user
fileName = JOptionPane.showInputDialog("Please specify which file you would like to write to: ");
//Create and opent the file for writing
FileWriter fWrite = new FileWriter(fileName,true);
PrintWriter outputFile = new PrintWriter(fWrite);
//This method should write the changed text to the file but it doesn't seem to be doing this...
outputFile.println(uppercaseLines);
//Close the files
inputFile.close();
outputFile.close();
}
}

Like I said, the problem is that there is nothing written to the output file. The file is created, but there is no text written to it. What's the problem?

Re: I'm trying to write to a file using the printwriter class.

Posted 03 April 2011 - 06:53 AM

Thanks. I think the problem was that I didn't close the files that were created within the program and right before I uploaded this post, I put the code in to close the files and I didn't think that would have anything to do with the output.