兩個函數如下:
TextToFile(..)函數:將字符串寫入給定文本文件;
createDir(..)函數:創建一個文件夾,有判別是否存在的功能。
1 public void TextToFile(final String strFilename, final String strBuffer) 2 { 3 try 4 { 5 // 創建文件對象 6 File fileText = new File(strFilename); 7 // 向文件寫入對象寫入信息 8 FileWriter fileWriter = new FileWriter(fileText); 9 10 // 寫文件 11 fileWriter.write(strBuffer); 12 // 關閉 13 fileWriter.close(); 14 } 15 catch (IOException e) 16 { 17 // 18 e.printStackTrace(); 19 } 20 } 21 public static boolean createDir(String destDirName) { 22 File dir = new File(destDirName); 23 if (dir.exists()) { 24 System.out.println("創建目錄" + destDirName + "失敗,目標目錄已經存在"); 25 return false; 26 } 27 if (!destDirName.endsWith(File.separator)) { 28 destDirName = destDirName + File.separator; 29 } 30 //創建目錄 31 if (dir.mkdirs()) { 32 System.out.println("創建目錄" + destDirName + "成功!"); 33 return true; 34 } else { 35 System.out.println("創建目錄" + destDirName + "失敗!"); 36 return false; 37 } 38 }
1 /** 2 * 功能:Java讀取txt文件的內容 3 * 步驟:1:先獲得文件句柄 4 * 2:獲得文件句柄當做是輸入一個字節碼流,需要對這個輸入流進行讀取 5 * 3:讀取到輸入流后,需要讀取生成字節流 6 * 4:一行一行的輸出。readline()。 7 * 備注:需要考慮的是異常情況 8 * @param filePath 9 */ 10 public static void readTxtFile(String filePath){ 11 try { 12 String encoding="utf-8"; 13 File file=new File(filePath); 14 if(file.isFile() && file.exists()){ //判斷文件是否存在 15 InputStreamReader read = new InputStreamReader( 16 new FileInputStream(file),encoding);//考慮到編碼格式 17 BufferedReader bufferedReader = new BufferedReader(read); 18 String lineTxt = null; 19 while((lineTxt = bufferedReader.readLine()) != null){ 20 System.out.println(lineTxt); 21 } 22 read.close(); 23 }else{ 24 System.out.println("找不到指定的文件"); 25 } 26 } catch (Exception e) { 27 System.out.println("讀取文件內容出錯"); 28 e.printStackTrace(); 29 } 30 31 }
