1

This is just for a simple command-line standalone program in Java.

I'd like to open a file to write to, and keep it open. I need to write formatted floats/doubles to it, in human-readable ASCII, like a CSV file.

I have tried various approaches (1) (2) (3) I have found through my favorite search engine, and they have the form:

try {
   // some file handle opening sequence
}
catch ( <some exception> ) {
  // do something
}
finally {
  // do something else
}

(...or in the case of the third example, the file opening/writing/closing is inside a function that throws an exception.) I realize it's good programming style to make sure that you've opened a file ok, but for my purposes that's really not necessary.

Anyway the problem with the above approach is that outside of the try{} block, the filehandle is closed. I'd like to keep it open, because the kernel of my code consists of a huge loop that I go through a few 100,000 times (say), and each time through I'd like to output a single float (in ASCII) to the file.

With the above form, the only way to do that is to enclose my huge for loop inside the try{} block. Which seems silly. Alternatively, I could re-open the file every time through the loop, but that means additional logic, opening the file as a 'new' file the first time, and appending in all subsequent times.

Is there some way to open the file, keep it open to write to it occasionally, and then close it when I'm done?

Something like:

{
// open file "data.out"
}
for (i=0;i<100000;i++) {
   // do a lot of stuff
   //
   // calculate some quantity "x"
   //
   // output float "x" in ASCII form, appending it to data.out
}
{
// close data.out
}

Does Java allow that? Thanks.

mrentropy
  • 57
  • 1
  • 3
  • 1
    _the only way to do that is to enclose my huge for loop inside the try{} block. Which seems silly._ What's so "silly" about that? – 001 May 31 '17 at 14:08
  • You can also open a file for writing at the end of the file and the information will be appended not overwritten.[public FileWriter(File file, boolean append)](http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter(java.io.File,%20boolean)) – Yuri H May 31 '17 at 14:14
  • Perhaps the word "silly" was ill-advised, but the reason I don't want to put my large loop inside another enclosing block is that it tends to reduce human-readability, since the loop might have 1000 lines of code in it, I have to scan the code for matching braces, and I might later decide that I want to open not just one file but two or three or even more files to write to. At some point that really does become cumbersome, if your large loop is three or more nested layers down inside successive try{} blocks. – mrentropy May 31 '17 at 14:18
  • You should then split your 1000 lines of code in several human-readable methods. And just wrap the caller method in a try/catch block. – Jeremy Grand May 31 '17 at 15:24
  • Beyond agreeing with @JeremyGrand, your IDE—as well your source code formatting—should help you visualize and navigate matching braces. – Tom Blodget May 31 '17 at 16:00
  • Methods should be short. A 1000 line method is bad, no matter if it is wrapped in a try-catch or not... – Florian Schaetz May 31 '17 at 18:48

2 Answers2

3

Of course you can simple store your FileWriter somewhere, as any other variable. You can, for example, encapsulate the whole writing logic in its own class, which offers one write method for your specified format.

But why does it seem silly? Perhaps this approach might help...

public void methodA(File myFile) throws IOException{
  try ( FileWriter writer = new FileWriter( myFile ) ) {
     writeTo(writer);
  }
}

private void writeTo(FileWriter writer) throws IOException {
   for (i=0;i<100000;i++) {
   // do a lot of stuff
   //
   // calculate some quantity "x"
   //
   // output float "x" in ASCII form, appending it to data.out
}

}

This way, one method takes care of the opening/closing/exceptions, while the other method can concentrate on the important writing stuff, using the FileWriter given to it.

Florian Schaetz
  • 10,454
  • 5
  • 32
  • 58
0

as you said the file is closed at the end of the try block. Possibly the FileWriter object is created inside the try block: (You did not post a real java code, only a pseudo code.)

Example, hope this helps

public static void main(String[] args) 
{
...
BufferedWriter ofs=null; // should by outside the try block

try
{ 
 Path logfile = Paths.set("C:\\temp\\log.log");

 ofs = Files.newBufferedWriter(logfile); // new in java 8

 YourWorker.doYourJob(ofs);

} catch (Exception e)
{   e.printStackTrace();
} finally
{
  if (ofs!=null) { try { ofs.close(); } catch (Exception e) {}   }
}
System.exit(1);     
} //---------- end of main()
} //---- end of class
Norbert
  • 234
  • 1
  • 9