如果一个文件太大,例如一个txt文件好几个G这时候使用Notepad是打不开的。两种查看文件内容的方法
第一种,将大文件切分成小文件后再使用Notepad。
public class SplitFileByLine {
public static void main(String[] args) throws IOException {
String datasetPath = "bigFilePath"; 大文件路径
String decPath = ""; //切分后文件存放的路径
int N = 6000; //指定每个切分后文件的行数
int i = 0;
int j = 1;
String filePath = decPath + "name";//就是切分后文件的名字
File filename = new File(filePath + j);
String newline = System.lineSeparator();
File file = new File(datasetPath);
LineIterator it = FileUtils.lineIterator(file);
while(it.hasNext()) {
if(i>=N) {
j++;
filename = new File(filePath + j);
i = 0;
}
String data = it.next() + newline;
FileUtils.writeStringToFile(filename, data, true); //最好的方法是一次读取指定行数的内容,一次性存入文件,这样子需要每一行都需要硬盘IO一次。
i++;
}
System.out.println("finish.");
}
}
第二种:直接读取前几十行。
方法二代码:
public class ReadContentFromFile {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String path="这里是路径";//就是大文件的路径。
File file=new File(path);
FileReader read=new FileReader(file);
BufferedReader reader=new BufferedReader(read);
String temp;
int i=0;
while((temp=reader.readLine())!=null){
System.out.println(temp);
i++;
if(i>20)
break;
}
}
}