java读取txt文件内容
通常配置文件写在xml中,今天的配置文件写在txt文档中
第一种方法:读取出来以字符串形式展示
1 import java.io.BufferedReader; 2 import java.io.File; 3 import java.io.FileInputStream; 4 import java.io.InputStreamReader; 5 6 public class ReadTxt { 7 8 public static void readTxtFile(String filePath){ 9 try { 10 String encoding="utf-8"; 11 File file=new File(filePath); 12 if(file.isFile() && file.exists()){ //判断文件是否存在 13 InputStreamReader read = new InputStreamReader( 14 new FileInputStream(file),encoding); //考虑到编码格式 15 BufferedReader bufferedReader = new BufferedReader(read); 16 String lineTxt = null; 17 while((lineTxt = bufferedReader.readLine()) != null){ 18 System.out.println(lineTxt); 19 } 20 read.close(); 21 } else { 22 System.out.println("找不到指定的文件"); 23 } 24 } catch (Exception e) { 25 System.out.println("读取文件内容出错"); 26 e.printStackTrace(); 27 } 28 } 29 30 public static void main(String args[]){ 31 ReadTxt readTxt = new ReadTxt(); 32 String filePath = readTxt.getClass().getClassLoader().getResource("").getPath() + "1.txt"; 33 readTxtFile(filePath); 34 } 35 }
第二种方法:读取出来转换成数组
1 import java.io.BufferedReader; 2 import java.io.FileInputStream; 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.io.InputStreamReader; 6 7 public class ReadArray { 8 public static String readFile(String filePath) throws IOException { 9 StringBuffer sb = new StringBuffer(); 10 InputStream is = new FileInputStream(filePath); 11 String line; // 用来保存每行读取的内容 12 BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 13 line = reader.readLine(); // 读取第一行 14 while (line != null) { // 如果 line 为空说明读完了 15 sb.append(line); // 将读到的内容添加到 buffer 中 16 sb.append("\n"); // 添加换行符 17 line = reader.readLine(); // 读取下一行 18 } 19 reader.close(); 20 is.close(); 21 return sb.toString(); 22 } 23 24 public static void main(String[] args) { 25 String filePath = "D:\\1.txt"; 26 try { 27 String strCont = readFile(filePath); 28 String [] stringArr= strCont.split("\n"); 29 System.out.println(stringArr.length); 30 for(int i=0; i<stringArr.length; i++){ 31 System.out.println(stringArr[i]); 32 } 33 } catch (IOException e) { 34 // TODO Auto-generated catch block 35 e.printStackTrace(); 36 } 37 } 38 }
浙公网安备 33010602011771号