Java IO

来源:互联网 发布:sql server的实际用途 编辑:程序博客网 时间:2024/06/09 19:58
  • 读取并修改文本文件
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