字节型
FileInputStream读取
package test;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.util.*;public class Test { public static void main(String[] args) { FileInputStream stream = null; try { stream = new FileInputStream(new File("./abc.txt")); byte[] value = new byte[5]; // 利用byte[]的方式读取 int count = stream.read(value); while (count != -1){ System.out.print(new String(value,0,count)); count = stream.read(value); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (stream != null) { stream.close(); } } catch (IOException e) { e.printStackTrace(); } }// File file = new File("./abc.txt");// try {// FileInputStream stream = new FileInputStream(file);// int i = stream.read();// stream.available(); // 有多少字节可用//// //byte[] value = new byte[5];// //stream.read(value); // 带byte[]参数的读取文件//// stream.skip(3); // 跳过几个字节// while (i != -1) {// System.out.print((char) i);// i = stream.read(); // 读取文件// }// stream.close(); // 关闭流通道,必须关闭// } catch (IOException e) {// e.printStackTrace();// } }}
FileOutputStream写入
package test;import java.io.*;import java.util.*;public class Test { public static void main(String[] args) { String str = "abcd"; FileOutputStream fos = null; try { // 如果没有这个文件就会自己创建 fos = new FileOutputStream(new File("./abc.txt"), true); // 用追加的方式写入 byte[] value = str.getBytes(); // 用byte[]的方法写 ,可以写入字节 fos.write(value); // 写入 fos.flush(); // 刷新 } catch (IOException e) { e.printStackTrace(); } finally { try { if (fos != null) { fos.close(); } } catch (IOException e) { e.printStackTrace(); } } }}
字符型
FileRead读取 只能渡纯文本
package test;import java.io.*;import java.util.*;public class Test { public static void main(String[] args) { File file = new File("./abc.txt"); FileReader reader = null; try { reader = new FileReader(file); //int code = reader.read(); // 读取单个字符 char[] chars = new char[1024]; int count = reader.read(chars); // 使用char数组 while (count != -1) { System.out.print(new String(chars,0 ,count)); count = reader.read(chars); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } } }}
FileWirte写入
package test;import java.io.*;import java.util.*;public class Test { public static void main(String[] args) { File file = new File("./abc.txt"); FileReader reader = null; FileWriter writer = null; try { writer = new FileWriter(file,true); String str = "我擦撒娇撒"; writer.write(str.toCharArray()); // char数组写入 writer.write('a'); writer.write(100); // char类型写入 writer.write("我"); // 字符串类型写入 writer.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (writer != null) { writer.close(); } } catch (IOException e) { e.printStackTrace(); } } }}