字节流读取文件内容FileInputStream
//把流定义在try()里,try,catch或者finally结束的时候,会自动关闭
try (FileInputStream fis = new FileInputStream(f)) {
byte[] all = new byte[(int) f.length()];
fis.read(all);
for (byte b : all) {
System.out.println(b);
}
} catch (IOException e) {
e.printStackTrace();
}
字节流向文件写入数据FileOutputStream
try {
File f = new File("d:/lol2.txt");
byte data[] = { 88, 89 };
FileOutputStream fos = new FileOutputStream(f);
fos.write(data);
} catch (IOException e) {
e.printStackTrace();
}finally {
// 在finally 里关闭流
if (null != fos)
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
字符流读取文件FileReader
try (FileReader fr = new FileReader(f)) {
char[] all = new char[(int) f.length()];
fr.read(all);
for (char b : all) {
System.out.println(b);
}
} catch (IOException e) {
e.printStackTrace();
}
字符流写入文件FileWriter
try (FileWriter fr = new FileWriter(f)) {
String data="abcdefg1234567890";
char[] cs = data.toCharArray();
fr.write(cs);
} catch (IOException e) {
e.printStackTrace();
}
缓存字符流可以一次读取一行数据BufferedReader
try (
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
)
{
while (true) {
// 一次读一行
String line = br.readLine();
if (null == line)
break;
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PrintWriter 缓存字符流可以一次写出一行数据
try (
// 创建文件字符流
FileWriter fw = new FileWriter(f);
// 缓存流必须建立在一个存在的流的基础上
PrintWriter pw = new PrintWriter(fw);
) {
pw.println("garen kill teemo");
pw.println("teemo revive after 1 minutes");
pw.println("teemo try to garen, but killed again");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
立即把数据写入到硬盘,而不是等缓存满了才写出去。 这时候就需要用到flush
对象流 写入ObjectOutputStream 读取ObjectInputStream
直接把一个对象以流的形式传输给其他的介质
把一个对象序列化有一个前提是:这个对象的类,必须实现了Serializable接口
import java.io.Serializable;
public class Hero implements Serializable {
//表示这个类当前的版本,如果有了变化,比如新设计了属性,就应该修改这个版本号
private static final long serialVersionUID = 1L;
public String name;
public float hp;
}
try(
//写入
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos =new ObjectOutputStream(fos);
//读取
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois =new ObjectInputStream(fis);
) {
oos.writeObject(h);
Hero h2 = (Hero) ois.readObject();
System.out.println(h2.name);
System.out.println(h2.hp);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Scanner读取字符串
Scanner s = new Scanner(System.in);
while(true){
String line = s.nextLine();
System.out.println(line);
}