JAVA获取txt文件内容

  JAVA 读取txt文件内容

  一般,咱们能够直接经过文件流来读取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 }

读取文件效果:

相关文章
相关标签/搜索