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;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42866384/article/details/81410952
今日推荐