文件I/O操作在java.io
包中
读取文件
使用FileInputStream
字节流读取文件
class Test{
public static void main(String []args){
try {
FileInputStream fis = new FileInputStream("test.txt");
byte[] data = new byte[1024];
while (fis.read(data) != -1) {
String s = new String(data);
System.out.println(s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用Reader
字符流读取文件
class Test {
public static void main(String []args) {
try (FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr)) {
String s;
while ((s = br.readLine()) != null) {
System.out.println(s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
写入文件
使用FileOutputStream
写入文件
class Test{
public static void main(String []args){
try {
FileOutputStream fos = new FileOutputStream("test.txt");
fos.write("abc".getBytes());
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用Writer
字符流写入文件
class Test {
public static void main(String []args) {
}
}
文件操作
使用File
进行文件操作
class Test{
public static void main(String []args){
try {
File f = new File("cooy.png");
f.createNewFile();
System.out.println(f.length()); // 0
System.out.println(f.canExecute()); // true
System.out.println(f.canRead()); // true
System.out.println(f.canWrite()); // true
System.out.println(f.isFile()); // true
System.out.println(f.isDirectory()); // false
f.delete();
} catch (IOException e) {
e.printStackTrace();
}
}
}
对象序列化
将对象写入文件
Serializable
接口
只有实现了Serializable
接口的类才能序列化
Serializable
接口中没有方法,仅用于标记
class Student implements Serializable {
private String stu_id;
private String name;
private Date birthday;
private float stu_score;
}
读写对象
使用ObjectInputStream
和ObjectOutputStream
读写对象
Object obj;
try (FileInputStream fis = new FileInputStream(fname);
ObjectInputStream ois = new ObjectInputStream(fis)) {
obj = ois.readObject();
} catch (Exception e) {
e.printStackTrace();
}
Serializable obj = new Student();
try (FileOutputStream fos = new FileOutputStream(fname);
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(obj);
} catch (Exception e) {
e.printStackTrace();
}