binary file input
- FileInputStream
- BufferedInputStream
InputStream in = new BufferedInputStream (new FileInputStream (fileName));
byte[] data = new byte[1024];
int length = in.read(data);
read() returns length of binary number it gets and save the number to data.
when it reads nothing, read() returns -1.
binary file output
- FileOutputStream
- BufferedInputStream
OutputStream out = new BufferedOutputStream (new FileOutputStream (fileName));
out.writer (data, 0, length);
writer() gets numbers of data from 0 to length, and saves them to file.
binary file io example
InputStream in = new BufferedInputStream (new FileInputStream (inFileName));
OutputStream out = new BufferedOutputStream (new FileOutputStream (outFileName));
byte[] data = new byte[1024];
int length = -1;
while ((length = in.read (data)) != -1) {
out.writer (data, 0, length);
}
in.close();
out.close();
it should be noticed that in and out must be close(), or the file will not be changed.
text file input
- File
- FileReader
- BufferedReader
File infile = new File (inFileName);
BufferedReader in = new BufferedReader (new FileReader(infile));
String s = in.readLine();
in.close();
if readLine() reads nothing, return null;
text file output
- File
- FileWriter
- BufferedWriter
File outfile = new File (outFileName);
BufferedWriter out = new BufferedWriter(new FileWriter(outfile));
out.println(s);
out.close();
text file io example
File infile = new File (inFileName);
File outfile = new File (outFileName);
BufferedReader in = new BufferedReader (FileReader (infile));
BufferedWriter out = new BufferedWriter (FileWriter (outFile));
String string = in.readLine();
while (string != null) {
out.println(string);
string = in.readLine();
}
in.close();
out.close();