您好,登錄后才能下訂單哦!
小編給大家分享一下如何使用java實現讀取txt文件并以在每行以空格取數據,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
簡單一個例子。其中正則是取消多余空格或者tab鍵
package test4; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class ExplaceSql { public static void main(String[] args) { String filePath = ExplaceSql.class.getResource("").getPath()+"aaa.txt"; // 文件路徑 read(filePath); } /** * 讀取內容 */ public static String read(String filePath){ BufferedReader br = null; String line =null; //StringBuffer buf = new StringBuffer(); try { //根據文件路徑創建緩沖輸入流 br = new BufferedReader(new FileReader(filePath));//filePath中是aaa.txt文件 String str = ""; //循環讀取文件的每一行,對需要修改的行進行修改,放入緩沖對象中 while ((line = br.readLine()) != null) { //設置正則將多余空格都轉為一個空格 str=line+"\r\n"; String[] dictionary = str.split("\\s{2,}|\t"); for(int i=0;i<dictionary.length;i++){ str = "insert into tablename values("+ dictionary[0]+",'"+dictionary[1]+"',"+dictionary[2]+"')"; } System.out.println(str); } } catch (Exception e) { e.printStackTrace(); }finally { if (br != null) {// 關閉流 try { br.close(); } catch (IOException e) { br = null; } } } return null; } }
java逐行讀寫txt文件
package help; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.HashMap; import java.util.Map; public class TXTParseUtils { private static final Integer ONE = 1; public static void main(String[] args) { Map<String, Integer> map = new HashMap<String, Integer>(); /* 讀取數據 */ try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("D:/報銷.txt")), "UTF-8")); String lineTxt = null; while ((lineTxt = br.readLine()) != null) { String[] names = lineTxt.split(","); for (String name : names) { if (map.keySet().contains(name)) { map.put(name, (map.get(name) + ONE)); } else { map.put(name, ONE); } } } br.close(); } catch (Exception e) { System.err.println("read errors :" + e); } /* 輸出數據 */ try { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("D:/結果.txt")), "UTF-8")); for (String name : map.keySet()) { bw.write(name + " " + map.get(name)); bw.newLine(); } bw.close(); } catch (Exception e) { System.err.println("write errors :" + e); } } }
看完了這篇文章,相信你對“如何使用java實現讀取txt文件并以在每行以空格取數據”有了一定的了解,如果想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。