• FileReader&FileWriter


    FileReader

    public static void main(String[] args) {
            //创建文件对象指定要读取的文件路径
            File file=new File("d:\readme1.txt");
            
            try {
                //创建文件字符输入流对象
                FileReader fr=new FileReader(file);
                /***********方法一(逐个字符读取文件中的信息)************************
                int ch;
                while((ch=fr.read())!=-1){
                    System.out.print((char)ch);
                }
                *************************************/
                
                /************方法二(以字符数组的方式进行读取)**********
                //创建字符数组
                char[] chs=new char[(int)file.length()];
                //将字符流中的数据读给字符数组
                fr.read(chs);
                //将字符数组转为字符串
                String s=new String(chs);
                System.out.println(s);
                
                System.out.println("===============");
                ********************************************/
                
                /****方法三(使用字符缓冲区读取文件中的内容)*****************/
                BufferedReader br=new BufferedReader(fr);
                String s=null;
                //br.readLine()表示逐行读取
                while((s=br.readLine())!=null){
                    System.out.println(s);
                }
                /******************************************/
            
                fr.close();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    FileWriter

    public static void main(String[] args) {
            Scanner sc=new Scanner(System.in);
            //创建文件对象,指定要输出的文件路径
            File file=new File("d:\aa.txt");
            
            System.out.println("请输入要保存的消息:");
            String msg=sc.next();
            
            try {
                //创建文件字符输出流对象,true表示可以再文件的末尾追加信息
                FileWriter fw=new FileWriter(file,true);
                fw.write(msg+"
    ");
                fw.flush();
                fw.close();
                System.out.println("文件保存成功!");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
  • 相关阅读:
    java做微信支付notify_url异步通知服务端的写法
    QT如何编译出带调试信息的qtwebkit库
    Vmware 占用宿主机硬盘空间只增不减
    vmware linux无法正常上网
    Linux中find常见用法示例
    计算机网络OSI参考模型与tcp/ip四层模型
    Core开发-后台任务利器Hangfire使用
    Azure构建PredictionIO和Spark的推荐引擎服务
    NET MVC+EF6+Bootstrap
    服务器
  • 原文地址:https://www.cnblogs.com/xh_Blog/p/6595100.html
Copyright © 2020-2023  润新知