文件读写

读文件: 先得到文件地址如:"E:\\old.txt",这里绝对路径时有'\',要用双的;

                 然后得到文件句柄:File file = new File("filePath");

                判断文件是否存在 if(file.isFile() && file.exists());

                 获得一个输入流,可以读文件:InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);

                 //endcoding 是一个String类型字符串,编码格式

                获得一个读入缓冲BufferedReader br = new BufferedReader(read);

                 然后开始读。

写文件:

               获得文件句柄:File file = new File("E:\\new.txt");

              得到输出流:OutputStream os = new FileOutputStream(file);

              得到一个打印流:PrintStream ps = new PrintStream(os);

              写:ps.print(String s);

注意:写文件时,经常不能写出换行

           因为写在s后加换行是s.append("\r\n");

源码:

public class CMain {

    public static void main(String[] args) {
        String filePath = "E:\\old.txt";

        StringBuffer buffer = new StringBuffer("Only a test\n");
        File file = new File("E:\\new.txt");
        try {
            OutputStream os = new FileOutputStream(file);
            readTxtFile(filePath, os);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("over!!!!!!");
    }
//读文件
    public static void readTxtFile(String filePath, OutputStream os) {
        try {
            String encoding = "GBK";
            File file = new File(filePath);
            if (file.isFile() && file.exists()) {
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file), encoding);
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    StringBuffer sb = new StringBuffer(lineTxt);
                    sb.append("\r\n");
                    writeFromBuffer(sb, os);
//                    writeFromBuffer("\r\n", os);
                }
                read.close();
            } else {
                System.out.println("找不到指定文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
    }
//写入
    public static void writeFromBuffer(StringBuffer buffer, OutputStream os) {
        PrintStream ps = new PrintStream(os);
        ps.print(buffer.toString());
    }
    
    public static void writeFromBuffer(String string, OutputStream os) {
        StringBuffer sb = new StringBuffer(string);
        writeFromBuffer(sb, os);
    }
}            

              

                

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值