HIT2019春软件构造->大文件读写方法NIO

Lab5 中需要进行大文件读写,以下是NIO方法的总结:

 

读取文件:

import java.nio.file.Files;

import java.nio.file.Paths;

利用Files.readAllBytes(Paths.get(filePath))获取filePath路径里面的文件的所有的内容,该方法返回一个字节数组,再调用new String()方法创建一个字符串。

public String input(String filePath) {
  String p=new String();
  try {
    p = new String(Files.readAllBytes(Paths.get(filePath)));
  } catch (IOException e) {
    e.printStackTrace();
  }
  return p; //返回文件内容到一个字符串中

  String[] ss = s.split("\n|\r"); //利用.split()方法分隔行
}

 

写回文件:

1.java.io.FileWriter

使用FileWriter类的write方法,将相应的字符串写回到路径当中:

public void output(String filename,String str) {
  FileWriter fw;
  try {
    fw = new FileWriter(filename);
    fw.write(str, 0, str.length());
    fw.close();
  } catch (IOException e) {
    e.printStackTrace();
  }
}


2.FileOutputStream

使用FileOutputStream类的write方法:

public void output(String filename, String str) {
  FileOutputStream fos;
  try {
    fos = new FileOutputStream(filename);
    fos.write(str.getBytes());
    fos.close();
  } catch (IOException e) {
    e.printStackTrace();
  }
}


3.BufferedOutputStream

使用BufferedOutputStream类的write方法:

public void output(String filename, String str) {
  BufferedOutputStream buff;
  try {
    buff = new BufferedOutputStream(new FileOutputStream(filename));
    buff.write(str.getBytes());
    buff.flush();
    buff.close();
  } catch (IOException e) {
    e.printStackTrace();
  }
}

posted @ 2019-06-16 22:03  阿洛萌萌哒  阅读(134)  评论(0编辑  收藏  举报