Help Required, Problem in writing a File.

H

hammad.afzal

Hello Dear Fellows.

I am having a problem in writing files. Problem seems to be very
trivial but I dont know, why I havent been able to figure it out. I am
pasing a code snippet below. Task is to read files from a directory,
process it a bit, and write again.

/* fileManager is an instance of userdefined class. Contents of
files are successfully read into StringBuffer contents*/

for (int n = 0; n < terms.length; n++)
{
StringBuffer strBuffer = new
StringBuffer(replacer_terms[n]);
contents.append(strBuffer);

contents.append(System.getProperty("line.separator"));
}
fileManager.fileWriter(contents,f2 + "\\Profile_" +
str);
System.out.println("Value of File is : " + str);
System.out.println("Value of Contents is : " +
contents);

f2 is a path of directory, and this code runs in a loop for all files
in direcory f2 where str is the name of the file in directory f2,
which is being processed. Problem is the last two lines also shows the
correct value, but I dont know why it is not writing into file.

The code of fileManager.fileWriter is here:
public void fileWriter(StringBuffer stringBuffer,String path)
{
try
{
File writeFile = new File(path);
OutputStream fout = new FileOutputStream(writeFile);
OutputStream bout = new BufferedOutputStream(fout);
OutputStreamWriter writer = new OutputStreamWriter(bout);
writer.write(stringBuffer.toString());
}
}


Kindly enlighted me if you figure out where lies the problem. Many
Thanks
 
O

Oliver Wong

The code of fileManager.fileWriter is here:
public void fileWriter(StringBuffer stringBuffer,String path)
{
try
{
File writeFile = new File(path);
OutputStream fout = new FileOutputStream(writeFile);
OutputStream bout = new BufferedOutputStream(fout);
OutputStreamWriter writer = new OutputStreamWriter(bout);
writer.write(stringBuffer.toString());
}
}


Kindly enlighted me if you figure out where lies the problem. Many
Thanks

You have to close the output streams when finished writing.

- Oliver
 
M

Madi

Thanks Oliver ..it worked ..:) .... I had written this method for
writing a single file...
and it worked well in that case,,,,
 
T

Thomas Hawtin

writer.flush();
} finally {
fout.close();
}
You have to close the output streams when finished writing.

More than that, you should always close resources, even if you get an
exception.

Tom Hawtin
 

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

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,736
Latest member
zacharyharris

Latest Threads

Top