写入本地文件
代码 fileOutputStream
public static void main(String[] args) { String hello ="hello world"; String filePath ="text.txt"; try (FileOutputStream fileOutputStream = new FileOutputStream(filePath);) { byte[] bytes = hello.getBytes(); fileOutputStream.write(bytes); System.out.println("文件写入成功:" + filePath); } catch (FileNotFoundException e) { System.out.println("异常:找不到文件!"); } catch (IOException e) { System.out.println("异常:文件写入失败!"); }
读取本地文件
代码FileInputStream
1.InputStreamReader是对FileInputStream进行包装
2.在中国使用UTF-8
3.StringBuilder是一种特殊的string可以更好地表示字符串
4.sb.append方法:把bytes里从0到尾的数据增加到sb里边
利用while循环把文件里所有内容读出
public static void main(String[] args) { String filePath = "text.txt"; try (FileInputStream fis = new FileInputStream(filePath); InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);) { char[] bytes = new char[1024]; StringBuilder sb = new StringBuilder(); int charlength; while ((charlength= isr.read(bytes))!=-1){ sb.append(bytes,0, charlength); } String string = sb.toString(); System.out.println("读取到的内容是" + string); } catch (IOException e) { System.out.println("文件操作异常"); }
流的概念(stream)
流的特点:单向的一维操作