java 文件读写

1,写到txt文本中     

public static void main(String[] args) throws Exception {
//          自动回填
           for(int i=0;i<10;i++) {
               writeText(String.valueOf(i),true);
           }
           
   }
   public static void writeText(String addData,boolean enter) {
       
       FileWriter fw = null;
       try {
           File f= new File("E:\testfile\csvTest.txt");
           fw = new FileWriter(f,true);
       }catch(IOException e) {
           e.printStackTrace();
       }
       PrintWriter pw = new PrintWriter(fw);
       if(enter) {
           pw.println(addData);
       }else {
           pw.print(addData+"|");       //  此处注意println和print的区别(换行/不换行)
       }
       pw.flush();
       try {
        fw.flush();
        pw.close();
        fw.close();
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }                     
   }
View Code

2,写到csv中

  /**
     *    自动填写预期
     *    注意:写入的操作每次都会重新写入,无法指定某行写入,只能一次写入全部内容
     *    @param CSVFileFullPath 路径
     *    @param header 表头
     *    
     *    @throws Exception
     *    
     */  
   public static void writeCSVFile(String CSVFileFullPath, String[] header) throws Exception {
//     将集合数据写入CSV文件
       CsvWriter csvWrite = new CsvWriter(CSVFileFullPath,',',Charset.forName("GB2312"));
       String[] value = null;
       
       csvWrite.writeRecord(header);
       ArrayList<String> testList = readAndWritelist();
       for(String data:testList) {
           value = data.split("\|");
           csvWrite.writeRecord(value);
//           csvWrite.endRecord();    // 换行
       }
       csvWrite.close();
       System.out.println("CSV写入成功!");
       System.out.println("文件保存路径:"+ CSVFileFullPath);       
}
   /**
    *    读写文本返回数据集合
    *    @return
    *    @throws FileNotFoundException
    */  
   
   @SuppressWarnings("resource")
   public static ArrayList<String> readAndWritelist() throws FileNotFoundException{
       Scanner scanner = new Scanner(new FileInputStream("csvTest.txt"));
//       通过FileInputStream构建Scannner
        ArrayList<String> testList = new ArrayList<String>();
       while(scanner.hasNext()) {
           String line = scanner.nextLine();  //读入一行数据
           testList.add(line);
       }
////       输出所有数据
//       for(String integerData:testList) {
//           System.out.println(integerData);
//       }
       
       return testList;
   }
View Code

3,在csv中读取数据

       /**
        * 读取CSV文件内容      --- 读取某一行的值
        * 
        * @param CSVFilepullPath      读取文件路径
        * @para ReadCaseNum   读取文件行号
        * 
        * @return
        * @throws Exception
        */
           public static  Map<String, String> ReadCSVFileLine(String CSVFilepullPath, Integer ReadCaseNum ) throws Exception{
               
               Integer Linenum = 1, i =0;
               String[] Header = null;
               Map<String,String> Result = new HashMap<String,String>();
//               生成CSVReader对象,以,为分隔符,BG2312编码方式
               InputStreamReader isr = new InputStreamReader(new FileInputStream(CSVFilepullPath), "GB2312");  
               CsvReader csvReader = new CsvReader(isr); 
               
//               CsvReader csvReader = new CsvReader(CSVFilepullPath, Charset.forName("GB2312"));
               
               
//           读取表头
               csvReader.readHeaders();
//           获取表头信息
               Header = csvReader.getHeaders();
//           跳转到要读取的行
               while(Linenum<ReadCaseNum) {
                   Linenum++;
                   csvReader.skipRecord();
               }
//               读取跳转到的行
               if(csvReader.readRecord()) {
                   for(i = 0;i<Header.length;i++) {
//                       按列名读取这条记录的值,放入map集合
                       Result.put(Header[i].trim(), csvReader.get(Header[i]));
                   }
                   System.out.println("##TestcaseNum is "+ReadCaseNum+""+Result);
                   
//                   取csv表格中的某一个值     -- 方法1
                   String aaJson = JSON.toJSONString(Result);
                   JSONArray jsonArray = JSONArray.parseArray("["+aaJson+"]");
                   JSONObject jsonObject = jsonArray.getJSONObject(0);
                   String note = jsonObject.getString("Note");                   
                   System.out.println("##note ==== "+""+note);
                   
//                   取csv表格中的某一个值  -- 方法2
                   String a = Result.get("Note");
                   System.out.println("##a ==== "+""+a);
                   
               }else {
                   ReadCaseNum++;
                   System.out.println("##Line"+ReadCaseNum+"tontext is empty");
                       
               }
               csvReader.close();       
               return Result;

           }
View Code

4,读取csv中的数据   ---- 方法2

     

    public static void main(String[] args) throws Exception {
       readeCsv();
       CsvUtil("e:/csvTest.csv");
       writeCsv();
    
}
       public static  void CsvUtil(String fileName) throws Exception {
            List<String> list = new ArrayList<String>();
                       
           InputStreamReader isr = new InputStreamReader(new FileInputStream(fileName), "GB2312");  
           BufferedReader br = new BufferedReader(isr); 

            
           String stemp;
           while ((stemp = br.readLine()) != null) {
                   list.add(stemp);
           }
           System.out.println("list========"+list);  
       }
    
/** 
* 读取CSV文件 
*/  
public static void  readeCsv(){  
    try {      
           
        ArrayList<String[]> csvList = new ArrayList<String[]>(); //用来保存数据  
        String csvFilePath = "e:/csvTest.csv";  
         CsvReader reader = new CsvReader(csvFilePath,',',Charset.forName("GB2312"));    
           
         reader.readHeaders(); // 跳过表头   如果需要表头的话,不要写这句。  
           
         while(reader.readRecord()){ //逐行读入除表头的数据      
             csvList.add(reader.getValues());  
         }      
      
         reader.close();  
         System.out.println(" csvList====== "+ csvList);   
           
         for(int row=0;row<csvList.size();row++){  
               
             String  cell = csvList.get(row)[1];       //取得第row行第0列的数据  
             System.out.println(" cell====== "+ cell);                                                   
         }                
    }catch(Exception ex){  
        System.out.println(ex);  
    }  
}  
  
/** 
 * 写入CSV文件 
 */  
public static void writeCsv(){  
    try {  
          
        String csvFilePath = "e:/test.csv";  
         CsvWriter wr =new CsvWriter(csvFilePath,',',Charset.forName("SJIS"));  
         String[] contents = {"aaaaa","bbbbb","cccccc","ddddddddd"};                      
         wr.writeRecord(contents);  
         wr.close();  
     } catch (IOException e) {  
        e.printStackTrace();  
     }  
}  
View Code
原文地址:https://www.cnblogs.com/147258llj/p/14408657.html