Created
February 1, 2012 19:45
-
-
Save tacitphoenix/1718871 to your computer and use it in GitHub Desktop.
Java|Scala IO
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Java | |
Write serialized object to a file | |
public static void writeFile(File dest) throws IOException{ | |
FileOutputStream fileStream = new FileOutputStream(dest); | |
ObjectOutputStream os = new ObjectOutputStream(fileStream); | |
os.writeObject(obj); | |
os.close(); | |
} | |
Read serialized object from a file | |
public static void writeFile(File source) throws IOException{ | |
FileInputStream fileStream = new FileInputStream(source); | |
ObjectInputStream os = new ObjectInputStream(fileStream); | |
Object obj = os.readObject(); | |
MyObj myObj = (MyObj) obj; | |
os.close(); | |
} | |
Write text to a file | |
public static void writeFile(File source) throws IOException{ | |
FileWriter writer = new FileWriter(source); | |
writer.write("How we write a text file in java"); | |
writer.close(); | |
} | |
Read text from a file | |
public static void main(File source) throws IOException{ | |
BufferedReader reader = new Buffered Reader(new FileReader(source)); | |
String line = null; | |
while((line = reader.readLine()) != null){ | |
System.out.println(line); | |
} | |
reader.close(); | |
} | |
Copy file via binary read/write | |
private static void copyFile(File source, File dest) throws IOException { | |
OutputStream out = new FileOutputStream(dest); | |
byte[] buffer = new byte[(int) source.length()]; | |
FileInputStream in = new FileInputStream(source); | |
in.read(buffer); | |
try { | |
out.write(buffer); | |
} finally { | |
out.close(); | |
in.close(); | |
} | |
} | |
Scala | |
Read text from file | |
for(line <- io.Source.fromFile(filename).getLines) println(line) | |
Write text to a file | |
val out = new PrintWriter(filename) | |
for (i <- 1 to 100) out.println(i) | |
out.close() | |
Read binary file | |
val in = new FileInputStream(new File(filename)) | |
val bytes = new Array[Byte](file.length.toInt) | |
in.read(bytes) | |
in.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment