一、文件读取和写入
1 try { 2 FileInputStream fis = new FileInputStream(fileName); 3 InputStreamReader isr = new InputStreamReader(fis,"UTF-8"); 4 BufferedReader br = new BufferedReader(isr); 5 String line; 6 StringBuilder sb = new StringBuilder(); 7 while ((line = br.readLine()) != null) 8 sb = sb.append(line+"\n"); 9 br.close(); 10 isr.close(); 11 fis.close(); 12 return sb.toString(); 13 } catch (FileNotFoundException e) { 14 // TODO Auto-generated catch block 15 e.printStackTrace(); 16 } catch (IOException e) { 17 // TODO Auto-generated catch block 18 e.printStackTrace(); 19 }
1 try { 2 FileOutputStream fos = new FileOutputStream(newFile); 3 OutputStreamWriter osw = new OutputStreamWriter(fos); 4 BufferedWriter bw = new BufferedWriter(osw); 5 bw.write(string); 6 System.out.println("文件写入成功"); 7 bw.close(); 8 osw.close(); 9 fos.close(); 10 } catch (FileNotFoundException e) { 11 // TODO Auto-generated catch block 12 e.printStackTrace(); 13 } catch (IOException e) { 14 // TODO Auto-generated catch block 15 e.printStackTrace(); 16 }
时间: 2024-10-01 07:24:26