java IO流读/取文件

package theFourth;

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;
import java.io.PrintWriter;

public class Test {
    static FileWriter fw = null;
    static PrintWriter pw=null;
    static InputStreamReader reader = null;
    static BufferedReader br=null;
    public static void Inputmethod(String address) {// 写文件

        try {
            // 如果文件存在,则追加内容;如果文件不存在,则创建文件
            File f = new File("D:\\"+address);//D:\\input.txt
            fw = new FileWriter(f, true);
        } catch (IOException e) {
            e.printStackTrace();
        }
         pw = new PrintWriter(fw);
        pw.println("追加内容");//如是在其他方法或main调用    将从此行一直到catch里面内容剪切过去即可
        pw.flush();
        try {
            fw.flush();
            pw.close();
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String Outputmethod(String address) {// 读文件
        String pathname = "D:\\"+address; // 绝对路径或相对路径都可以,这里是绝对路径,写入文件时演示相对路径
        File filename = new File(pathname); // 要读取以上路径的input。txt文件

        String string="";
        try {
            reader = new InputStreamReader(new FileInputStream(filename));
             br = new BufferedReader(reader); // 建立一个对象,它把文件内容转成计算机能读懂的语言
            while (true) {
                String line = br.readLine(); // 一次读入一行数据
                if (line != null) {
                    //System.out.println(line);
                    string=string+line+"";
                }
                else
                {
                    break;
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            reader.close();
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return string;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值