java读写文件 txt
java读取txt文件
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.util.ArrayList;
/**
* create by fzg
* 2022/11/17 15:16
*/
@Slf4j
public class ReadeTxtFile {
public static void main(String[] args) {
read();
}
public static void read(){
// 文件位置换成你自己的位置
String fileUrl = "E:\\学习\\项目\\vue-vant-app\\myBlog\\myCaveolae_server\\src\\main\\java\\com\\fzg\\common\\demo\\readWriteTxt\\demo01.txt";
File file = new File(fileUrl);
if (file.exists()){
ArrayList<String> arr = new ArrayList<>();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
String info = null;
while ((info = br.readLine()) != null){
arr.add(info);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("文件不存在");
} catch (IOException e){
e.printStackTrace();
System.out.println("文件读取失败");
}finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
log.info(arr.toString());
}else {
log.info("文件不存在");
}
}
}
java 写入字符串到txt文件
package com.fzg.common.demo.readWriteTxt;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
/**
* create by fzg
* 2022/11/17 14:53
* 写入TXT文件
*/
@Slf4j
public class WriteTxtFile {
public static void main(String[] args) {
write();
}
public static void write() {
Scanner scanner = new Scanner(System.in);
// 输入:用Scanner类的hasNextLine方法判断
System.out.println("请输入:");
String str = "";
if (scanner.hasNextLine()){
str = scanner.nextLine();
log.info(str);
}
if (str.equals("")){
System.out.println("输入为空");
}else {
// 换成你自己的位置
File file = new File("E:\\学习\\项目\\vue-vant-app\\myBlog\\myCaveolae_server\\src\\main\\java\\com\\fzg\\common\\demo\\readWriteTxt\\demo01.txt");
FileWriter fw = null;
try {
fw = new FileWriter(file,true);
try {
fw.write(str);
fw.close();
System.out.println("文件写入成功!");
}catch (Exception e){
System.out.println("文件写入失败");
}
fw.close();
} catch (IOException e) {
System.out.println("未找到文件");
e.printStackTrace();
}
}
}
}