文件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接口中没有方法,仅用于标记
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(); }