Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

FileWriter or Scope question 1

Status
Not open for further replies.

pozitron969

Programmer
May 14, 2002
29
0
0
US
Hello,

I am trying to write a simple class that will open a file, append a line to the file until you type exit. This is what I have so far. I am getting two errors when I compile the code below. The only things that I can think of is that I am not handling the FileWriter object correctly when I pass it back from the openFile procedure or that the myOut object is out of scope when I try to pass it back to the writeLine and closeFile procedures. Thank you in advance.



fileio_input.java [38:1] variable myOut might not have been initialized
{writeLine(myOut,sLine);}
^
fileio_input.java [43:1] variable myOut might not have been initialized
{closeFile(myOut);}
^
2 errors
Errors compiling.


import java.io.*;
import javax.swing.*;
import java.lang.*;

/*
* fileio_input.java
*
* Created on November 23, 2003, 10:08 PM
*/

/**
*
* @author me
*/
public class fileio_input {

/** Creates a new instance of fileio_input */
public fileio_input() {
}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String sLine;
String sFile;
FileWriter myOut;

sFile = JOptionPane.showInputDialog("Enter a Filename:");
try
{myOut = openFile(sFile);}
catch (IOException exception){}

do
{
sLine = JOptionPane.showInputDialog("Enter a line of text:");
try
{writeLine(myOut,sLine);}
catch (IOException exception){}
}
while (!sLine.equals("exit"));
try
{closeFile(myOut);}
catch (IOException exception){}
System.exit (0);
}

public static FileWriter openFile(String thisFile) throws IOException {
File thisOutFile = new File(thisFile);
FileWriter thisOut = new FileWriter(thisOutFile);
return thisOut;
}
public static void writeLine(FileWriter thisOut,String thisLine) throws IOException {
thisOut.write(thisLine);
}
public static void closeFile(FileWriter thisOut) throws IOException
{thisOut.close();}
}
 
You need :
FileWriter myOut = null;

instead of : FileWriter myOut;

- the object needs to be initialized ...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top