java利用IO对文件进行操作,包括新建文件、文本写入文件、文件内容读取
代码:
package try_1;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.Scanner;
public class do_file {
//文本写入文件
public static void write(String filePathAndName,String fileContent) {
try {
File myFilePath = new File(filePathAndName);
// if (!myFilePath.exists()) {
// myFilePath.createNewFile();
//}
//FileWriter resultFile = new FileWriter(myFilePath);
FileWriter resultFile = new FileWriter(myFilePath,true);// 表示在原文件的基础上添加内容
PrintWriter myFile = new PrintWriter(resultFile);
myFile.println(fileContent);
//将内容写入文件
myFile.close(); resultFile.close();
System.out.println("文件写入操作成功!");
} catch (IOException e) {
System.out.println("新建文件操作出错!");
e.printStackTrace();
}
}
//新建文件
public static void newFile(String filePathAndName, String fileContent) {
try {
File myFilePath = new File(filePathAndName);
if (!myFilePath.exists()) {
myFilePath.createNewFile();
}
FileWriter resultFile = new FileWriter(myFilePath);
// FileWriter resultFile = new FileWriter(myFilePath,true); 表示在原文件的基础上添加内容
PrintWriter myFile = new PrintWriter(resultFile);
myFile.println(fileContent);
//将内容写入文件
myFile.close(); resultFile.close();
System.out.println("新建文件操作成功!");
} catch (IOException e) {
System.out.println("新建文件操作出错!");
e.printStackTrace();
}
}
//读文件
public static void visit() {
try{
FileInputStream fis = new FileInputStream("F:\\QQ文件\\2.txt"); //定义一个文件字节流
InputStreamReader isr = new InputStreamReader(fis); //将字节流转换成字符流
BufferedReader br = new BufferedReader(isr); //将字符流转换成缓存流
String s=""; String ss ="";
while((s = br.readLine())!= null) { //一次读取一行
ss += s+"\n";
}
br.close(); isr.close(); fis.close();
System.out.print(ss);
}
catch(IOException e){
e.printStackTrace();
}
}
public static void main(String args[]) {
//newFile("F:\\QQ文件\\2.txt","abcd\n1234\n5678");
Scanner input=new Scanner(System.in);
String m=input.nextLine();
write("F:\\QQ文件\\2.txt",m);
visit();
}
}
运行截图: