使用Java创建文本文档并填充数据——FileWriter基本应用
一切尽在代码块中
package IO.MyFile;
import java.io.*;
public class MyFile_01 {
public static void main(String[] args) throws IOException {
File file = new File("word.txt");//创建文件对象
String content[] = {"好久不见","最近好吗","常联系"};
//写入
FileWriter writer = new FileWriter(file);//创建FileWriter类对象
BufferedWriter bufferedWriter = new BufferedWriter(writer);//创建BufferedWriter对象
for (int i = 0; i < content.length; i++) {
bufferedWriter.write(content[i]);//将字符串数组的元素写入磁盘文件
bufferedWriter.newLine();//以单行形式写入
}
bufferedWriter.close();//关闭BufferedWriter流
writer.close();//关闭FileWriter流
//读取
FileReader fileReader = new FileReader(file);//创建FileReader类对象
BufferedReader bufferedReader = new BufferedReader(fileReader);//创建BufferedReader对象
String s = null;
int i = 0;
//如果文件的文本行数不为null,则循环
while ((s = bufferedReader.readLine()) != null){
i++;
System.out.println("第"+i+"行:"+s);//输出数据
}
bufferedReader.close();//关闭BufferedReader流
fileReader.close();//关闭FileReader流
}
}
将得到一个名为“word.txt”的文本文档,并带有内容: