java文本复制和键盘输入文字保存到文件

java文本复制和键盘输入文字保存到文件,第1张

java文本复制和键盘输入文字保存到文件

通过下面的案例了解Java的i/o流基本知识,为了方便看清代码的逻辑,所以异常均抛出去

一:完成文本复制,有三种方法,大家可以测测他们的性能。

``
`

`package com.yxy;

import java.io.*;

public class TestCopy {

    public static void main(String[] args) throws IOException {
        
        File file=new File("D:"+File.separator+"test.txt");
        File file1=new File("D:"+File.separator+"test1.txt");
        
        FileReader fileReader=new FileReader(file);
        BufferedReader bufferedReader=new BufferedReader(fileReader);
        FileWriter fileWriter=new FileWriter(file1);
        
        BufferedWriter bufferedWriter=new BufferedWriter(fileWriter);


       
        int n = bufferedReader.read();
        while (n!=-1){
            bufferedWriter.write(n);
            n=bufferedReader.read();
        }


        
        char ch[]=new char[5];
        int len = bufferedReader.read(ch);
        while (len!=-1){
            bufferedWriter.write(ch,0,len);
            len=bufferedReader.read(ch);
        }
        
        String s = bufferedReader.readLine();
        while (s!=null){
            bufferedWriter.write(s);
            bufferedWriter.newline();
            s=bufferedReader.readLine();
        }
        
        bufferedWriter.close();
        bufferedReader.close();
    }
}



二:键盘输入保存到文件中

package com.yxy;

import java.io.*;

public class Test01 {
    public static void main(String[] args) throws IOException {
        InputStream in=System.in;
        InputStreamReader inputStreamReader=new InputStreamReader(in);
        BufferedReader bufferedReader=new BufferedReader(inputStreamReader);

        
        File file=new File("D:"+File.separator+"test2.txt");
        FileWriter fileWriter=new FileWriter(file);
        BufferedWriter bufferedWriter=new BufferedWriter(fileWriter);
        
        String s = bufferedReader.readLine();
        
        while (!"exist".equals(s)){
            bufferedWriter.write(s);
            bufferedWriter.newline();
            s=bufferedReader.readLine();
        }
        bufferedWriter.close();
        bufferedReader.close();
    }

}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5676363.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存