Java方法讀取文件內容
一.針對文件內容的讀取,在平時的工作中想必是避免不了的操作,現在我將自己如何用java方法讀取文件中內容總結如下:廢話不多說,直接上代碼:
方法一:
public static void main(String[] args) throws IOException { FileInputStream fileInputStream = null; try { // 1.獲取文件指定的文件信息 fileInputStream = new FileInputStream("D:\\softwore\\workspace\\springbootdemo\\node10-boot-mybatis\\src\\main\\resources\\test.txt"); // 2.將數據讀到字節數組里 byte[] buff = new byte[1024]; int length = fileInputStream.read(buff); // 3.將字節數據轉換為字符串 // 參數一:帶轉換的字節數組,參數二:起始位置 參數三:轉換的長度 String info = new String(buff, 0, length); System.out.println(info); } catch (IOException e) { e.printStackTrace(); } finally { // 4,關閉流操作 if (fileInputStream != null) fileInputStream.close(); }
}
1.文件存放位置

2.結果如下:

方法二:(此方法是讀取resource目錄下對應文件名的文件內容)
public static void main(String[] args) throws IOException { InputStream inputStream = null; BufferedReader reader = null; StringBuilder content = new StringBuilder(); try { inputStream = Test03.class.getClassLoader().getResourceAsStream("test.txt"); if (Objects.nonNull(inputStream)) { reader = new BufferedReader(new InputStreamReader(inputStream)); } else { throw new RuntimeException("test.txt not found"); } String line = ""; while ((line = reader.readLine()) != null) { content.append(line); } System.out.println(content.toString()); } catch (IOException e) { throw new RuntimeException(e); } finally { if (Objects.nonNull(inputStream)) { inputStream.close(); } if (Objects.nonNull(reader)) { reader.close(); } } }
1.輸出結果如下:

古今成大事者,不唯有超世之才,必有堅韌不拔之志!

浙公網安備 33010602011771號