IO分为字节流和字符流
字节流:是8位通用字节流,其单位是字节。(FileInputStream,FileOutputStream)
字符流:是16位unicode字符流,基本单位是unicode字符,最适合处理文字或字符串。(BufferedReader,BufferedWriter)
// --字节流
FileOutputStream out = null;
try {
out = new FileOutputStream(new File("c:\\a.txt"));
byte[] by = "accept".getBytes();
out.write(by);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
FileInputStream input = null;
try {
input = new FileInputStream(new File("c:\\a.txt"));
while (input.available() != 0) {
System.out.println((char) input.read());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// --字符流
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("c:\\a.txt"));
String str;
while ((str = reader.readLine()) != null) {
System.out.println(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
BufferedWriter bwout = null;
try {
bwout = new BufferedWriter(new FileWriter("c:\\a.txt"));
String str2;
str2 = "hello world!世界,你好!";
bwout.write(str2);
bwout.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bwout.close();
} catch (IOException e) {
e.printStackTrace();
}
}