Java中读取/写入txt文件

Java对txt文件读取与写入操作

直接上代码

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;


public class ReadTxt {
	/**传入txt路径读取txt文件
     * @param txtPath
     * @return 返回读取到的内容
     */
    public static String readTxt(String txtPath) {
        File file = new File(txtPath);
        if(file.isFile() && file.exists()){
            try {
                FileInputStream fileInputStream = new FileInputStream(file);
                InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                
                StringBuffer sb = new StringBuffer();
                String text = null;
                while((text = bufferedReader.readLine()) != null){
                	sb.append(text);
                    sb.append("\n"); //换行
                }
                return sb.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    
    /**使用FileOutputStream来写入txt文件
     * @param txtPath txt文件路径
     * @param content 需要写入的文本
     */
    public static void writeTxt(String txtPath,String content){    
       FileOutputStream fileOutputStream = null;
       File file = new File(txtPath);
       try {
           if(!file.exists()){
               //判断文件是否存在,如果不存在就新建一个txt
        	   System.out.println("原来没有这个文件,现在创建一个···");
        	   file.createNewFile();
           } else {
        	   System.out.println("原来有这个文件,直接写入");
        	   fileOutputStream = new FileOutputStream(file);
        	   fileOutputStream.write(content.getBytes());
        	   fileOutputStream.flush();
        	   fileOutputStream.close();
           }
       } catch (Exception e) {
           e.printStackTrace();
       }
    }
    
    // 主函数,用来测试读写函数
    public static void main(String[] args){	
    	/**
    	 * 调用读文件函数readTxt并输出
    	 */
        writeTxt("D:/myh/result.txt", "测试写入txt文件内容");
        String str = readTxt("D:/myh/result.txt");
        System.out.println(str); 
    }
}

注意:createNewFile()函数
返回值为boolean类型,用来判断文件是否创建成功
用法:boolean b = file.createNewFile();
如果原来没有指定的文件,则创建一个指定路径的文件,此时文件创建成功,则b的值为true;
如果有指定的文件,那么文件创建失败,此时返回值为false。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MYH永恒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值