java IO流读写文件

这里我简单记录一下java IO流读写本地文件


java IO流从本地读取文件:

import java.io.BufferedReader;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.InputStreamReader;  
  
public class Read {  
    public static void main(String[] args) {  
        read("E://123.txt");  
    }  
  
    public static void read(String file) {  
        String s = null;  
        StringBuffer sb = new StringBuffer();  
        File f = new File(file);  
        if (f.exists()) {  
            try {  
                BufferedReader br =  
                    new BufferedReader(new InputStreamReader(new FileInputStream(f)));  
                while ((s = br.readLine()) != null) {  
                    sb.append(s);  
                }  
                System.out.println(sb);  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        } else {  
            System.out.println("文件不存在!");  
        }  
    }  
}  


java IO流往本地文件写数据

import java.io.*;  
  
public class write {  
    public static void main(String[] args) {  
        write("E://123.txt", "hello");  
    }  
  
    public static void write(String path, String content) {  
        String s = new String();  
        String s1 = new String();  
          
        try {  
            File f = new File(path);  
              
            if (f.exists()) {  
                System.out.println("文件存在");  
            } else {  
                System.out.println("文件不存在,正在创建...");  
                if (f.createNewFile()) {  
                    System.out.println("文件创建成功!");  
                } else {  
                    System.out.println("文件创建失败!");  
                }  
            }  
              
            BufferedReader input = new BufferedReader(new FileReader(f));  
  
            while ((s = input.readLine()) != null) {  
                s1 += s + "/n";  
            }  
              
            System.out.println("文件内容:" + s1);  
            input.close();  
            s1 += content;  
            BufferedWriter output = new BufferedWriter(new FileWriter(f));  
            output.write(s1);  
            output.close();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
}   



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值