Pages

Monday, October 22, 2012

File save in java and python

Python

Python has really simple and intuitive interface for file saving.
f = open("/Users/smcho/Desktop/hello.txt", "w")
f.write("string")
f.close()
In case you realize that 'try/catch' is missing, you can add that easily.
f = open("hello.txt", "wb")
try:
    f.write("Hello Python!\n")
finally:
    f.close()
Or, you can use the wiz (with as).
with open("hello.txt", "wb") as f:
    f.write("Hello Python!\n")
You can get some hints on python's with as from this post.

Java

Java needs a chain of objects to write string to a file : File object -> FileWriter object (you don't need to specify "w") -> BufferedWriter. Check this post.
File file = new File (canonicalFilename);
BufferedWriter out = new BufferedWriter(new FileWriter(file)); 
out.write(text);
out.close();
This code is using Decorator design pattern, as BufferedWriter() wraps around the FileWriter object, and FileWriter does to the File object. One needs to import some modules, and let the method know it will throw some error. So, the full code should be as follows:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

class Example {
 public static void main(String[] args) throws IOException {
  File file = new File ("/Users/smcho/Desktop/hello.txt");
  BufferedWriter out = new BufferedWriter(new FileWriter(file)); 
  out.write("Hello, world");
  out.close();
 }
}
You can also process the error processing on your own, as this post shows.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

class Example {
 public static void main(String[] args) {
  try {
   File file = new File ("/Users/smcho/Desktop/hello.txt");
   BufferedWriter out = new BufferedWriter(new FileWriter(file)); 
   out.write("Hello, world");
   out.close();
  }
  catch (IOException e) {
   e.printStackTrace();
  }
 }
}

No comments:

Post a Comment