关闭

[置顶] Java IO

标签: java
162人阅读 评论(0) 收藏 举报
分类:
  • 读取并修改文本文件
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();
        }
    }

}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:42686次
    • 积分:896
    • 等级:
    • 排名:千里之外
    • 原创:57篇
    • 转载:12篇
    • 译文:1篇
    • 评论:3条
    文章分类
    最新评论