Java文件

JAVA读取和写入


ctl文件换行使用

import java.io.*;
import java.util.regex.Pattern;

/**
 * 文件读取和写入
 */
public class FileReader {

    public static void main(String[] args) {
        //初始文件
        File f =new File("D:\\11.txt");
        BufferedReader bufferedReader = null;
        StringBuffer buffer = null;
        try {
            //读取文件
            bufferedReader= new BufferedReader(new java.io.FileReader(f));
            //存取数据
            buffer = new StringBuffer();
            String  temp = "";
            //匹配开头"21
            Pattern pattern = Pattern.compile("^\"21");
            //按行读取
            while ((temp=bufferedReader.readLine())!=null){
                //if(!temp.startsWith("21")){
                //匹配部分
                if(!pattern.matcher(temp).find()){
                //匹配全部
                //if(!pattern.matcher(temp).matches()){
                    buffer.append("\\r\\n").append(temp);
                } else{
                    buffer.append("\n").append(temp);
                }
            }
            //输出日志
            System.out.println(buffer.toString());
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //输出文件
        File file = new File("D:\\22.txt");
        FileOutputStream fileOutputStream =null;
        try {
            //判断文件存在否
            if (!file.exists()){
                file.createNewFile();
            }
            fileOutputStream = new FileOutputStream(file);
            //写入文件
            fileOutputStream.write(buffer.toString().getBytes());
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值