像我們經常會遇到這樣的事情,例如一個txt檔案中有姓名和電話,這個時候很經常就需要將名字和電話號碼進行提取操作,這個時候就可以利用Java中io來實現了。 這裡我就不具體介紹io中的位元組流和字元流的異同點了,有興趣的同學可以自己百度百度。 今天主要是介紹一下如何?對檔案內容的擷取還有就是對擷取的檔案內容進行修改操作。下面看具體案例介紹。 這個是案例最終要實現的效果,在姓名和電話號碼直接添加分割符號。 這裡有一點需要主要的是,這個案例並不是直接在原先的txt文檔上面進行修改的,而是建立一個新的txt檔案重新寫入新的內容。 好了廢話不多說,看看這個案例具體是怎麼具體實現的。 這個案例分為三個模組:1.檔案讀模數塊,2.姓名電話分離模組,3.檔案寫入模組
1.檔案讀模數塊:
/** * 功能:Java讀取txt檔案的內容 * 步驟:1:先獲得檔案控制代碼 * 2:獲得檔案控制代碼當做是輸入一個位元組碼流,需要對這個輸入資料流進行讀取 * 3:讀取到輸入資料流後,需要讀取產生位元組流 * 4:一行一行的輸出。readline()。 * 備忘:需要考慮的是異常情況 * @param filePath */public static String readTxtFile(String filePath) {StringBuilder content = new StringBuilder("");try {String encoding = "UTF-8";File file = new File(filePath);if (file.isFile() && file.exists()) {InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);BufferedReader bufferedReader = new BufferedReader(read);String lineTxt = null;while ((lineTxt = bufferedReader.readLine()) != null) {String[] result = getNamePhone(lineTxt);System.out.println(lineTxt);content.append(result[0] + "----" + result[1]);content.append("\r\n");// txt換行}read.close();} else {System.out.println("找不到指定的檔案");}} catch (Exception e) {System.out.println("讀取檔案內容出錯");e.printStackTrace();}return content.toString();}
2.姓名電話分離模組:
public static String[] getNamePhone(String str) {String[] result = new String[2];int index = 0;for (int i = 0; i < str.length(); i++) {if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {index = i;break;}}result[0] = str.substring(0, index);result[1] = str.substring(index);return result;}
3.檔案寫入模組:
public static void printFile(String content) {BufferedWriter bw = null;try {File file = new File("D:/filename.txt");if (!file.exists()) {file.createNewFile();}FileWriter fw = new FileWriter(file.getAbsoluteFile());bw = new BufferedWriter(fw);bw.write(content);bw.close();} catch (IOException e) {e.printStackTrace();}}
通過這三個模組就可以實現對檔案的讀取操作了,然後對資訊進行處理,最後將處理好的資訊添加到新的檔案中去。 這裡需要注意的是:項目的編碼格式要寫成utf-8,否則會出現亂碼的情況。 到這裡檔案的讀寫操作就完結了,是不是特別簡單方便。
如果對上面的內容還有什麼疑義或者問題都可以加我QQ:208017534諮詢。