Java文件IO
按字符读写Reader、Writer
FileWrite、FileReader
FileWriter writer = new FileWriter(file, true)
为追加写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public static void main(String[] args) throws Exception { String dir = "E:\\aaa.txt"; File file = new File(dir); if (!file.exists()) file.createNewFile(); FileWriter writer = new FileWriter(file); writer.write("aaa"); writer.flush(); writer.close();
FileReader reader = new FileReader(file); char[] ch = new char[100]; reader.read(ch); for (char c : ch) { System.out.print(c); } System.out.println(); reader.close(); }
|
通过套一层BufferedWrite、BufferedReader,可以一行行来读
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| public static void main(String[] args) throws Exception { String dir = "E:\\aaa.txt"; File file = new File(dir); if (!file.exists()) file.createNewFile(); BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.write("aaa"); bw.flush(); bw.close();
BufferedReader br = new BufferedReader(new FileReader(file)); String line; while ((line = br.readLine()) != null) { System.out.println(line); } System.out.println(); br.close(); }
|
FileOutputStream、FileInputStream
FileOutputStream fos = new FileOutputStream(file, true)
为追加写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| public static void main(String[] args) throws Exception { String dir = "E:\\aaa.txt"; File file = new File(dir); if (!file.exists()) file.createNewFile(); FileOutputStream fos = new FileOutputStream(file); fos.write("aaa".getBytes()); fos.close();
FileInputStream fis = new FileInputStream(file); byte[] bys = new byte[100]; while (fis.read(bys, 0, bys.length) != -1) { System.out.println(new String(bys)); } fis.close(); }
|