InputStream
参考链接:
/** * Author:Mr.X * Date:2017/10/9 17:11 * Description: * @read():一个一个字节的读(单字节读取) */public class Demo1 { public static void main(String[] args) throws IOException{ FileInputStream fis = new FileInputStream("e:/abc.txt"); int by = 0; while ((by = fis.read()) != -1) { System.out.print((char) by); } fis.close(); }}
/** * Author:Mr.X * Date:2017/10/9 17:12 * Description: * * @read(byte[] buf):先把字节存入到缓冲区字节数组中,一下读一个数组(常用) * @即(多字节读取) */public class Demo2 { public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream(new File("e:/abc.txt")); int len = 0; byte[] buf = new byte[1024]; while ((len = fis.read(buf)) != -1) { System.out.print(new String(buf, 0, len)); } fis.close(); }}
因为中文占用2Byte,英文占用1Byte,所以按照一个一个字节的读取得时,中文是要出问题的!
单个字节流只能操作英文,不能操作中文,所以要一次性读取多个字节才能读取中文信息! abc.txt编码为uft-8,如果为其他编码的话,需要使用到字符流(专门用于操作字符)设置编码,不然中文会出问题!OutputStream
参考链接:
public class Demo1 { public static void main(String[] args) throws IOException { FileOutputStream fos = new FileOutputStream("e:/b.txt"); fos.write(65); fos.write(66); fos.write(67); fos.write(68); String str = " hello word!"; fos.write(str.getBytes()); fos.close(); }}
public class Demo2 { public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream(new File("e:/abc.txt")); FileOutputStream fos = new FileOutputStream("e:/b.txt"); int len = 0; byte[] buf = new byte[1024]; while ((len = fis.read(buf)) != -1) { fos.write(buf, 0, len); } fos.close(); fis.close(); }}