IO练习与小结

写入练习,简易记事本功能

public class Note {
    
    
    public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
    
    
        Scanner scan = new Scanner(System.in);
        System.out.println("请输入文件名");
        String fileName = scan.nextLine();

        FileOutputStream fos =new FileOutputStream(fileName);
        OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");
        BufferedWriter bw = new BufferedWriter(osw);

        PrintWriter pw = new PrintWriter(bw);

        while (true){
    
    
            System.out.println("请记事");
            String msg = scan.nextLine();
            if ("exit".equals(msg)){
    
    
                break;
            }
            pw.println(msg);
        }
        System.out.println("over");
        pw.close();
    }
}

读取操作

public class ReadDemo {
    
    
    public static void main(String[] args) throws IOException {
    
    
        FileInputStream fis = new FileInputStream("1.txt");
        InputStreamReader isr = new InputStreamReader(fis);
        BufferedReader br = new BufferedReader(isr);
        /*
        * BufferedReader可以读取一行字符串信息,直接使用String类型接受
        * */
        String msg = null;
        while ((msg=br.readLine())!=null){
    
    
            System.out.println(msg);
        }
        System.out.println("over");
        br.close();
    }
}

小结

在这里插入图片描述

おすすめ

転載: blog.csdn.net/sinat_33940108/article/details/120850889