创建、读取、写入txt文件

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
public static boolean creatTxtFile(String filePath) throws IOException{  //创建文本方法
		boolean flag=false; 
		File newF=new File(filePath);
		if(!newF.exists()){
			try{
				newF.createNewFile();
			}catch(IOException e){
				e.printStackTrace();
			}
			flag=true;
		}
		return flag;
	}
      /**
	 * 以这个路径创建一个阅读缓冲器:FileInputStream——>InputStreamReader——>BufferedReader
	 * @param filepath
	 * @return
	 * @throws IOException 
	 */
	public static String readTxtFile(String filepath) throws IOException{
		String result="";//存放读取结果
		String thisLine=null;//存放读取的行值
		File file=new File(filepath);
		if(file.exists()&&file.isFile())//判断是否存在该文件以及是否是正确的文件格式
		{
			try{
				BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(filepath)));
				while((thisLine=br.readLine())!=null)
				{
					result+=thisLine+"\n";//逐行读取
				}
				br.close(); //释放资源			
			}catch(FileNotFoundException e){
				e.printStackTrace();
			}
		}
		return result;
	}
public static boolean writeTxtFile(String content,String filePath,boolean append){  //通过append参数来控制写入形式,当append为true时追加写入,当append为false时为覆盖写入
		boolean flag=false;
		File thisFile=new File(filePath);
		try{
			if(!thisFile.exists()){
				thisFile.createNewFile();//不存在则创建该文件
			}
			FileWriter fw=new FileWriter(filePath,append);
			fw.write(content);
			fw.close();
			flag=true;
		}
		catch(IOException e){
			e.printStackTrace();
		}
		return flag;
		}

猜你喜欢

转载自blog.csdn.net/Xuhan666/article/details/80218253