![](https://img.51dongshi.com/20250108/wz/18393348052.jpg)
Java讀取文本文件的方法主要包括從指定位置文件中一行一行讀取內容,并將每行存入List集合。這是代碼示例:public static List readInputByRow(String path) { List list=new ArrayList(); File file=new File(path); try { FileInputStream fis = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); BufferedReader reader = new BufferedReader(isr); String tempstring=""; while((tempstring=reader.readLine())!=null) { list.add(tempstring); } reader.close(); isr.close(); fis.close(); return list; } catch (IOException e) { e.printStackTrace(); return null; }}另一種方法是從指定位置文件中讀取指定一行數據。代碼如下:public static String readInputByRow(String path,int num) { File file=new File(path); try { FileInputStream fis = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); BufferedReader reader = new BufferedReader(isr); String tempstring=""; int line=1; while((tempstring=reader.readLine())!=null) { if(line==num){ break; } line++; } reader.close(); isr.close(); fis.close(); return tempstring;}catch (IOException e) {e.printStackTrace();return null;}這兩種方法都涉及到文件的輸入流處理,以及使用BufferedReader逐行讀取文件內容。需要注意的是,錯誤處理部分會打印異常信息,并在發生異常時返回null。在實際應用中,這些方法可以靈活運用,根據需求讀取文件的不同部分。同時,為了提高效率和代碼的可維護性,建議對輸入參數進行適當的校驗和異常處理。此外,還可以考慮使用try-with-resources語句來自動關閉資源,簡化代碼并提高可讀性。例如:public static List readInputByRow(String path) { List list=new ArrayList(); File file=new File(path); try (FileInputStream fis = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); BufferedReader reader = new BufferedReader(isr)) { String tempstring=""; while((tempstring=reader.readLine())!=null) { list.add(tempstring); } return list;} catch (IOException e) { e.printStackTrace(); return null;}這種方式不僅簡化了代碼,還能確保資源被正確關閉。