一、读取文件
有两种方式,一是从缓冲流里读,一种是Scanner读取。前者是读取普通文件,先获取全部内容到缓冲流里,然后依次读取。后者适合读取大文件,读一行,取一行。推荐后者
/**
* 通过缓冲流读取文件
* @param path
*/
public static void normal(String path){
File file = new File(path);
if(file.exists()&&file.isFile()){
try {
InputStreamReader reader = new InputStreamReader(new FileInputStream(file));
BufferedReader buf = new BufferedReader(reader);
String line = "";
try {
while((line = buf.readLine())!=null){
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
/**
* 通过Scanner读取大文件
* @param path
*/
public static void bigFileRead(String path){
File file = new File(path);
try {
FileInputStream in = new FileInputStream(file);
Scanner scan = new Scanner(in,"UTF-8");
while(scan.hasNextLine()){
String line = scan.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
二、写文件
写文件同样有两种方式,覆盖式写入和追加式写入。前者是写过一次后,再次写入,这次所写的内容会覆盖掉之前的内容。后者是写过一次后,再次写入,这次所写的内容会追加到之前内容的后面,之前的内容依旧存在。推荐使用后者。
/**
* 再次写入内容会覆盖掉之前的内容,慎用!!!
*
* @param file
* @param str
*/
public static void replaceWrite(File file, String str) {
// 创建一个空文件
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
// 写入内容
if (file.isFile() && file.length() == 0) {
try {
FileOutputStream out = new FileOutputStream(file);
PrintStream p = new PrintStream(out);
p.print(str);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
/**
* 此方法是追加写入内容的,不会覆盖之前写入的内容,推荐使用!!
* @param file
* @param str
*/
public static void appendWrite(File file,String str){
//创建一个空文件
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
//写入内容
try {
BufferedWriter out = new BufferedWriter(new FileWriter(file,true));
out.write(str);
out.write("\r\n");//换行
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}