InputStream
OutputStream
FileInputStream
FileOutputStream
FileInputStream in = null;
try {
in = new FileInputStream("in_file.txt");
} finally {
if (in != null) {
in.close();
}
}
FileOutputStream out = null;
try {
out = new FileOutputStream("out_file.txt");
} finally {
if (out != null) {
out.close();
}
}
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("in_file.txt");
out = new FileOutputStream("out_file.txt");
int c;
while ((c = in.read()) != -1) { // read
out.write(c); // write
}
} catch (IOException io) {
// handle exception
} finally {
// close both streams
}
FileInputStream in = null;
try {
...
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ioe) {
// handle exception
}
}
try (FileInputStream in = new FileInputStream("in_file.txt")) {
in.read();
...
} catch (IOException ioe) {
// handle exception
}
Reader
Writer
FileReader
FileWriter
try (FileReader in = new FileReader("in_file.txt")) {
char [] a = new char[50];
in.read(a); // reads the content to the array
} catch (IOException ioe) {
// handle exception
}
try (FileWriter out = new FileWriter("out_file.txt")) {
out.write("This\n is\n an\n example\n");
out.flush();
} catch (IOException ioe) {
// handle exception
}
// input stream
BufferedInputStream bis =
new BufferedInputStream(
new FileInputStream("in_file.txt"));
// output stream
BufferedOutputStream bos =
new BufferedOutputStream(
new FileOutputStream("out_file.txt"));
// input stream
BufferedReader reader =
new BufferedReader(
new FileReader("in_file.txt"));
// output stream
BufferedWriter writer =
new BufferedWriter(
new FileWriter("out_file.txt"));
System.in
System.out
System.err
Console
System.console
PrintStream
PrintWriter
try (Scanner inputScanner =
new Scanner(System.in);
Scanner fileScanner =
new Scanner(new FileReader(“f.txt"));
Scanner stringScanner =
new Scanner("someString")) {
while (inputScanner.hasNext()) {
String line = inputScanner.nextLine();
...
}
}
public class Person {
String name;
int age;
boolean isMale;
}
Person person = new Person();
// writing
DataOutputStream dos =
new DataOutputStream(
new FileOutputStream("data.bin"));
dos.writeChars(person.getName());
dos.writeInt(person.getAge());
dos.writeBoolean(person.isMale());
// reading
DataInputStream dis =
new DataInputStream(
new FileInputStream("data.bin"));
person.setName(dis.readUTF());
person.setAge(dis.readInt());
person.setMale(dis.readBoolean());
public class Person implements Serializable {
String name;
int age;
boolean isMale;
}
Person person = new Person();
// writing
ObjectOutputStream ous =
new ObjectOutputStream(
new FileOutputStream("data.bin"));
ous.writeObject(person);
//reading
ObjectInputStream ois =
new ObjectInputStream(
new FileInputStream("data.bin"));
person = (Person) ois.readObject();