java讀取TXT文件


  1. 首先獲得一個文件句柄。File file = new File(); file即為文件句柄。兩人之間連通電話網絡了。接下來可以開始打電話了。

  2. 通過這條線路讀取甲方的信息:new FileInputStream(file) 目前這個信息已經讀進來內存當中了。接下來需要解讀成乙方可以理解的東西

  3. 既然你使用了FileInputStream()。那么對應的需要使用InputStreamReader()這個方法進行解讀剛才裝進來內存當中的數據

  4. 解讀完成后要輸出呀。那當然要轉換成IO可以識別的數據呀。那就需要調用字節碼讀取的方法BufferedReader()。同時使用bufferedReader()的readline()方法讀取txt文件中的每一行數據。



package campu; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; public class TxtR { public static void readTxtFile(String filePath){ try { String encoding="GBK"; File file=new File(filePath); if(file.isFile()&&file.exists()){ InputStreamReader read=new InputStreamReader(new FileInputStream(file),encoding); BufferedReader bufferedReader=new BufferedReader(read); String lineTxt=null; while((lineTxt=bufferedReader.readLine())!=null){ System.out.println(lineTxt); } read.close(); }else{ System.out.println("找不到指定文件!"); } } catch (Exception e){ System.out.println("讀取文件內容錯誤"); e.printStackTrace(); } } public static void main(String[] args) { String filePath="E:\\ribao.txt"; readTxtFile(filePath); } }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM