对文件的操作,例:txt文件

/*public class Message {
	private String username;
	private String Message;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getMessage() {
		return Message;
	}
	public void setMessage(String message) {
		Message = message;
	}
	
}*/

/**
 * txt文件创建、追加内容、读取内容
 * @author LuoPiao
 *
 */
public class MyTxt {
	
	public static void createTxt(String path) {
		File txt=new File(path);
		if(!txt.exists()) {
			if(path!=null&&!path.equals("")&&path.endsWith(".txt")) {
				try {
					txt.createNewFile();
				} catch (IOException e) {
					throw new RuntimeException("创建文件失败");
				}
			}	
		}
	}
	
	public static void writeTxt(String path,Message message) {
		createTxt(path);
		try (FileWriter writer = new FileWriter(path,true);//第二个参数为追加写入
                BufferedWriter out = new BufferedWriter(writer)
           ){
               out.write(message.getUsername()+":"+message.getMessage()+"\r\n"); // \r\n即为换行
               out.flush(); // 把缓存区内容压入文件
           }catch (IOException e) {
           e.printStackTrace();
       }
	}
	public static void writeTxt(String path,String message) {
		createTxt(path);
		try (FileWriter writer = new FileWriter(path,true);//第二个参数为追加写入
                BufferedWriter out = new BufferedWriter(writer)
           ){
               out.write(message+"\r\n"); // \r\n即为换行
               out.flush(); // 把缓存区内容压入文件
           }catch (IOException e) {
           e.printStackTrace();
       }
	}
	
	 public static List<String> readFile(String path) {
		   createTxt(path);
		   List<String> list=new ArrayList<String>();
	        try (FileReader reader = new FileReader(path);
	             BufferedReader br = new BufferedReader(reader) 
	        ) {
	            String line;
	            while ((line = br.readLine()) != null) {
	              list.add(line);
	            }
	        } catch (IOException e) {
	            e.printStackTrace();
	        }     
	        return list;
	    }
}

猜你喜欢

转载自blog.csdn.net/qq_37575994/article/details/100008545