open FileWriter in main function and pass in as parameter

M

moongeegee

I open a file by using FileWriter in main() function, the code as
below. I want to pass the outputStream
as parameter as foo(str,outputStream). Please help.

try {
FileWriter outputStream = new FileWriter("out.txt",true);
....
}
catch(...) {
}
foo(str,outputStream);
 
K

Knute Johnson

moongeegee said:
I open a file by using FileWriter in main() function, the code as
below. I want to pass the outputStream
as parameter as foo(str,outputStream). Please help.

try {
FileWriter outputStream = new FileWriter("out.txt",true);
....
}
catch(...) {
}
foo(str,outputStream);

FileOutputStream fos = null;
try {
fos = new FileOutputStream("file.name");
foo(str,fos);
} catch (IOException ioe) {
ioe.printStackTrace();
}

You can't mix writers and streams. Pick one or the other. The example
above uses streams. With the scheme above, if your file doesn't exist
or for whatever reason it throws an IOException your foo method won't
get called and blow up that code.
 
P

Piotr Kobzda

moongeegee said:
try {
FileWriter outputStream = new FileWriter("out.txt",true);
....
}
catch(...) {
}
foo(str,outputStream);

IIUC, and your problem is a scope of the local, try the following:

FileWriter outputStream;
try {
outputStream = new FileWriter("out.txt",true);
....


piotr
 
P

Patricia Shanahan

Piotr said:
IIUC, and your problem is a scope of the local, try the following:

FileWriter outputStream;
try {
outputStream = new FileWriter("out.txt",true);
....


piotr

Depending on what is in the catch block, outputStream may not be
definitely assigned at the end of the try-catch. If there are definite
assignment problems, initialize it in its declaration.

FileWriter outputStream = null;

Of course, the code should be written so that the null initialization
will not reach the use after the try-catch, for example because of a
System.exit call.

Patricia
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,570
Members
45,045
Latest member
DRCM

Latest Threads

Top