比如将内容(假设是字符串str)写入文件。步骤如下:
1.获取目标文件的地址,来实例化文件变量file。
File file = new File(“D:\IdeaProjects\javase\src\IOStream”);
2.用上述文件变量file,来实例化输出流fileOut。
FileOutputStream fileOut = new FileOutputStream(file);
(也可以:FileOutputStream fileOut = new FileOutputStream(“D:\IdeaProjects\javase\src\IOStream”);
与步骤1、2的效果相同。)
3.创建字节数组,将字符串str存储到字节数组中
String str = “learning practice”;
byte[] b = str.getBytes();
4.利用write()方法将字节数组的内容写入文件
fileOut.write(b);
5.刷新缓冲区的数据,类似于保存
fileOut.flush();
6.关闭输出流,节省资源
fileOut.close();
实现结果:learning practice写入了文件
实现代码:
FileOutputStream fileOut = null;try {// //若没有目录则创建,创建目录函数:file1.mkdirs();// File file1 = new File("src/step2/output");// //若没有文件则创建文件,创建文件函数:file2.createNewFile();// File file2 = new File("src/step2/output/output.txt");// try {// file1.mkdirs();// file2.createNewFile();// } catch (IOException e) {// e.printStackTrace();// }//读取文件地址String fileStr = "D:\\IdeaProjects\\javase\\src\\IOStream";//文件输出流,将内容写入到文件fileOut = new FileOutputStream(fileStr);//fileOut = new FileOutputStream(file2); 此语句与上一条语句等价//将字符串str转换成字节流fileOut.write(byte);String str = "learning practice";byte[] b = str.getBytes();//写入文件fileOut.write(b);//刷新缓冲器的数据,类似保存fileOut.flush();} catch (Exception e) {e.printStackTrace();} finally {//关闭输出流,节省资源try {fileOut.close();} catch (IOException e) {e.printStackTrace();}}}
