Java IO

  • 读取并修改文本文件
public class App {
    private LinkedList<String> list;

    public void fun() throws IOException {
        list = new LinkedList<String>();
        FileReader fr = new FileReader("d:/7.txt");
        BufferedReader br = new BufferedReader(fr);
        System.out.println("原内容是:");
        String str = null;
        while ((str = br.readLine()) != null) {
            System.out.println(str);
            list.add(str);
        }
        br.close();
    }

    public void print() throws IOException {
        this.fun();
        System.out.println("处理后内容是:");
        for (int i = list.size() - 1; i >= 0; i--)
            System.out.println(list.get(i));
    }

    public static void main(String args[]) throws IOException {
        App t7 = new App();
        t7.print();
    }
}
  • 复制文本/非文本文件
public class App {

    public void copy() throws IOException {
        FileInputStream fis = new FileInputStream("d:/img.jpg");
        BufferedInputStream bis = new BufferedInputStream(fis);
        FileOutputStream fos = new FileOutputStream("d:/img_copy.jpg");
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        int len = 0;
        while ((len = bis.read()) != -1) {
            bos.write(len);
        }
        bis.close();
        bos.close();
    }

    public static void main(String[] args) {
        App t1 = new App();
        try {
            t1.copy();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
    }

}
  • 将控制台输入的内容保存到文本文件
public class App {

    public void fun() throws IOException {
        File file = new File("d:\\3.txt");
        Scanner sc = new Scanner(new BufferedInputStream(System.in));// 控制台输入
        System.out.print(">");
        String str = sc.nextLine();
        PrintStream ps = new PrintStream(file);
        while (!str.equals("quit")) {
            ps.println(str);
            System.out.print(">");
            str = sc.nextLine();
        }
        sc.close();
        ps.close();
    }

    public static void main(String[] args) {
        App t3 = new App();
        try {
            t3.fun();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值