序言:使用IO操作读写
1、读取
@Test public void readeFile() { FileInputStream input = null; String result = ""; try { //1.根据path实例化一个输入流的对象 input = new FileInputStream("/Users/tentsuuhou/Desktop/潜台词.txt"); //2.返回这个输入流中可以被读的剩下的bytes字节的估计值; int size = input.available(); //3.根据输入流的字节创建一个byte数组 byte[] array = new byte[size]; //4.把数据读取到byte数组中 input.read(array); //5.根据获取的byte数组新建一个字符串,然后输出 result = new String(array); System.out.println(result); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if(input != null){ try { input.close(); } catch (IOException e) { e.printStackTrace(); } } } }
2、写入
@Test public void writeFile() { FileOutputStream out = null; String content = "我爱开源中国"; try { //1.根据路径创建输出流对象 out = new FileOutputStream("/Users/tentsuuhou/Desktop/777.txt") ; //2.把String字符串转换成byte数组; byte[] b = content.getBytes(); //3.把byte数组输出 out.write(b); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if(out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } }