FileOutputStream、FileInputStream和BufferedOutputStream、FileInputStream 应用

xiaoxiao2021-02-28  95

FileOutputStream、FileInputStream和BufferedOutputStream、FileInputStream 组合向磁盘上读写数据

package cn.lf.day0831; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Scanner; import org.junit.Test; //public byte[] getBytes() //我的理解:把String转为字符数组 public class IODemo4 { @Test public void test() throws FileNotFoundException, IOException{ File file = new File("./test/a.txt"); //文件路径 System.out.println("请输入内容:"); String content = new Scanner(System.in).next(); //写入的内容 writeToFileOutputStream(file, content); //写数据 // String str = readToFileInputStream(file); // System.out.println(str); } //写数据方法 //文件输出流:写数据到文件中去 public void writeToFileOutputStream(File file, String content) throws IOException, FileNotFoundException { // 第二个参数:是否追加到文件末尾 FileOutputStream fos = new FileOutputStream(file, true); //写数据缓冲区 BufferedOutputStream bos = new BufferedOutputStream(fos); // byte[] bs = content.getBytes(); // fos.write(bs); // fos.flush(); // fos.close(); bos.write(content.getBytes()); bos.flush(); bos.close(); } /** * @param file * @return * @throws IOException */ //文件输入流:读取文件内容 public String readToFileInputStream(File file) throws IOException{ String content = null; FileInputStream fis = new FileInputStream(file); //读数据缓冲区 BufferedInputStream bis = new BufferedInputStream(fis); byte[] bs = new byte[1024]; //int l = fis.read(bs); int l = bis.read(bs); //System.out.println(l); //System.out.println(Arrays.toString(bs)); content = new String(bs); // fis.close(); bis.close(); return content; } }
转载请注明原文地址: https://www.6miu.com/read-53555.html

最新回复(0)