JAVA 读取txt文件内容
通常,我们可以直接通过文件流来读取txt文件的内容,但有时可能会出现乱码!此时只要设置一下文件字符编码即可。
1 1 import java.io.BufferedReader; 2 2 import java.io.File; 3 3 import java.io.FileReader; 4 4 5 5 6 6 public class txttest { 7 7 /** 8 8 * 读取txt文件的内容 9 9 * @param file 想要读取的文件对象 1010 * @return 返回文件内容 1111 */ 1212 public static String txt2String(File file){ 1313 String result = ""; 1414 try{ 1515 BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件 1616 String s = null; 1717 while((s = br.readLine())!=null){//使用readLine方法,一次读一行 1818 result = result + "\n" +s; 1919 } 2020 br.close(); 2121 }catch(Exception e){ 2222 e.printStackTrace(); 2323 } 2424 return result; 2525 } 2626 2727 public static void main(String[] args){ 2828 File file = new File("D:/luceneData/test1.txt"); 2929 System.out.println(txt2String(file)); 3030 } 3131 }
读取文件效果:
