博主首页

文件写入一行 、读取一行的工具类案例,写入文件末尾,追加写入文件

  java 写入文件一行数据

  java读取文件一行数据

  只是案例代码

 

 采用编码方式

        InputStreamReader read = new InputStreamReader(new FileInputStream(file),"utf-8");
            BufferedReader br=new BufferedReader(read);

 

    /**
     * 判断该坐标是否已经转换
     */
    public static String isRead(String str) {
        
     try {    
         File file = new File("parseLocation.txt");
            if(!file.exists()){
                file.createNewFile();
            }
        BufferedReader br = new BufferedReader(new FileReader(file));// 构造一个BufferedReader类来读取文件
        String line ="";
          while ((line = br.readLine()) != null) {   
              
              if((line.substring(0,line.indexOf(":"))).equals(str)){
                  return line.substring(line.indexOf(":")+1);
              }
            }
          br.close();
        } catch (Exception e) {
            // TODO: handle exception
        }
        
        return "1";        
    }
    
    /**
     * 写入文件
     */
    public static void write(String key,String val) {    
        try {
            if(!"1".equals(isRead(key))){
                return;
            };
            File file = new File("parseLocation.txt");
            if(!file.exists()){
                file.createNewFile();
            }
         FileOutputStream stream = new FileOutputStream(file, true);
            stream.write((key+":"+val+System.getProperty("line.separator")).getBytes());
            stream.flush();        
            stream.close();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

 获取文件行号、获取文件行数

        LineNumberReader br = new LineNumberReader(new FileReader(fileStr));
        Integer index = map.get("index");
        String line="";
        while ((line=br.readLine())!=null){
            int lineNumber = br.getLineNumber();
            if(lineNumber>index){
                out.write((line+System.getProperty("line.separator")).getBytes());
            }
            if(lineNumber-index>=3000){
                break;
            }
        }

获取文件总行数

          long index=0;
                        boolean exists = Files.exists(Paths.get(filePath));
                        if(exists){
                            index =Files.lines(Paths.get(filePath)).count();
                        }

 

posted @ 2019-01-23 15:52  笑~笑  阅读(284)  评论(0编辑  收藏  举报