您的位置:首页 > 编程语言 > Java开发

Java读取文件内容和写入内容到文件

2017-10-10 11:12 435 查看
Java读取文件内容方法和写入内容到文件方法

/**
* One.txt中的数据如下:
* 1
* 2
* 3
* 4
* 5
* -----------------
* 读操作方法
*/
@Test
public void readFileToList2() {
File file = new File("C:\\Users\\Desktop\\One.txt");
System.out.println("文件绝对路径 :"+file.getAbsolutePath());
List<String> listStr = new ArrayList<String>();
BufferedReader br = null;
String str = null;
try {
br = new BufferedReader(new FileReader(file));
while ((str = br.readLine())!= null) {
listStr.add(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
System.out.println(listStr);
writeListToFile(listStr);// 调用写操作方法
}

/**
* 实现写操作方法
*/
private void writeListToFile(List<String> listStr) {
File file = new File("C:\\Users\\Desktop\\Azzan.txt");// 要写入的文件路径
if (!file.exists()) {// 判断文件是否存在
try {
file.createNewFile();// 如果文件不存在创建文件
System.out.println("文件"+file.getName()+"不存在已为您创建!");
} catch (IOException e) {
System.out.println("创建文件异常!");
e.printStackTrace();
}
} else {
System.out.println("文件"+file.getName()+"已存在!");
}

for (String str : listStr) {// 遍历listStr集合
FileOutputStream fos = null;
PrintStream ps = null;
try {
fos = new FileOutputStream(file,true);// 文件输出流	追加
ps = new PrintStream(fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String string  = str + "\r\n";// +换行
ps.print(string); // 执行写操作
ps.close();	// 关闭流

}

System.out.println("文件写入完毕!");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息