zoukankan      html  css  js  c++  java
  • java 读写文件

    1. 读文件

    import java.io.*;
    import java.util.*;
    
    public class test {
        public void test_readfile(String filePath){
            File file = new File(filePath);
            FileReader fr = null;
            BufferedReader reader = null;
            try{
                fr = new FileReader(file);
                reader = new BufferedReader(fr);
                String tmpString = "";
                while((tmpString = reader.readLine()) != null){
                    System.out.println(tmpString);
                }
            }
            catch (FileNotFoundException e){
                e.printStackTrace();
            }
            catch (IOException e){
                e.printStackTrace();
            }
            finally {
                try{
                    reader.close();
                    fr.close();
                }
                catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    
    
        public static void main(String []args){
            test case1 = new test();
            String filePath = "D:\test.txt";
            case1.test_readfile(filePath);
        }
    }

    2. 逐行写文件

    import java.io.*;
    import java.util.*;
    
    public class test {
        public void test_writefile(String filePath){
            File file = new File(filePath);
            FileWriter fw = null;
            BufferedWriter writer = null;
            try{
                fw = new FileWriter(file);
                writer = new BufferedWriter(fw);
                writer.write("hello");
                writer.newLine(); //换行
                writer.flush();
    
                writer.write("123");
                writer.newLine();
            }
            catch(FileNotFoundException e){
                e.printStackTrace();
            }
            catch (IOException e){
                e.printStackTrace();
            }
            finally {
                try{
                    writer.close();
                    fw.close();
                }
                catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    
    
        public static void main(String []args){
            test case1 = new test();
            String filePath = "D:\test.txt";
            case1.test_writefile(filePath);
        }
    }

    3. 乱码问题解决

    http://blog.csdn.net/greenqingqingws/article/details/7395213

    https://my.oschina.net/heweipo/blog/384509#comment-list

  • 相关阅读:
    559. N叉树的最大深度
    999. 车的可用捕获量
    1051. 高度检查器
    238. 除自身以外数组的乘积
    【Go】Go语言的%d,%p,%v等占位符的使用
    【Java】commons-lang3中DateUtils类方法介绍
    【Java】时间戳与Date相互转换
    【Linux】crontab定时任务用用法
    【Java】使用Lambda排序集合
    【PBFT】拜占庭容错
  • 原文地址:https://www.cnblogs.com/kaituorensheng/p/5920722.html
Copyright © 2011-2022 走看看