一般,咱們能夠直接經過文件流來讀取txt文件的內容,但有時可能會出現亂碼!此時只要設置一下文件字符編碼便可。java
1 import java.io.BufferedReader; 2 import java.io.File; 3 import java.io.FileReader; 4 5 6 public class txttest { 7 /** 8 * 讀取txt文件的內容 9 * @param file 想要讀取的文件對象 10 * @return 返回文件內容 11 */ 12 public static String txt2String(File file){ 13 String result = ""; 14 try{ 15 BufferedReader br = new BufferedReader(new FileReader(file));//構造一個BufferedReader類來讀取文件 16 String s = null; 17 while((s = br.readLine())!=null){//使用readLine方法,一次讀一行 18 result = result + "\n" +s; 19 } 20 br.close(); 21 }catch(Exception e){ 22 e.printStackTrace(); 23 } 24 return result; 25 } 26 27 public static void main(String[] args){ 28 File file = new File("D:/luceneData/test1.txt"); 29 System.out.println(txt2String(file)); 30 } 31 }