package com.java.bytestreams;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileOutputStreamDriver {
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("test.data");
String s = "This program writes a string to a file named test.data";
byte[] b = s.getBytes();
for (int i = 0; i < b.length; i++) {
fos.write(b[i]);
}
fos.close();
} // end -try
catch (IOException e) {
System.err.println(e);
}
}
}
The following example makes use of two classes to copy an input file to an output file.
1. Running CopyFile.java from Eclipse
When running the following file in Eclipse, make sure the file "input.txt" is at the same level as your 1) bin and 2) src folders.
Let us use a file input.txt with the following content.
This is test for copy file.
package com.java.bytestreams;
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
1. Running CopyFile.java from the Command Prompt
a) Compile the above program.
Put the above code in CopyFile.java file and execute the following from the command line on Unix or Linux machine.
$javac CopyFile.java
b) Execute CopyFile.java, which will result in creating the output.txt file with the same content as the "input.txt" file.
$java CopyFile
Ad
Java7 NIO 2