java讀取txt文本中如含有中文,可能會出現亂碼,解決方案是:
1.要統一編碼,java工程的編碼,txt文本編碼,java工程中的java文本編碼都統一為utf-8;
2.利用InputStreamReader(new FileInputStream(fileUrl), "utf-8")將文字再次設定為utf-8
3.具體程式碼如下
InputStreamReader isr; try { isr = new InputStreamReader(new FileInputStream(fileUrl), "utf-8"); BufferedReader read = new BufferedReader(isr); String s=null; List<String> list = new ArrayList<String>(); while((s=read.readLine())!=null) { //System.out.println(s); if(s.trim().length()>1){ list.add(s.trim()); } } System.out.println("OK!"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace();
更多java 逐行讀取txt請關注PHP中文網!