Java มีหลายเมธอดสำหรับอ่านไฟล์ แต่ละเมธอดเหมาะกับการอ่านชนิดไฟล์ต่างๆ ในสถานการณ์ต่างกัน บางตัวดีสำหรับไฟล์ยาว บางตัวสำหรับไฟล์สั้น ฯลฯ
ในบทช่วยสอนนี้ เราจะใช้ Java classes ต่อไปนี้ในการอ่านไฟล์
- BufferedReader
- Files
- Scanner
ตลอดบทช่วยสอน เราใช้ไฟล์เก็บใน directory src ที่ path ไปยังไฟล์คือ src/file.txt
เก็บหลายบรรทัดของข้อความในไฟล์นี้ก่อนดำเนินต่อ
หมายเหตุ: คุณต้องจัดการ errors อย่างเหมาะสมเมื่อใช้ implementations นี้ เพื่อปฏิบัติตาม best coding practices
การอ่าน Text Files ใน Java ด้วย BufferedReader
Class BufferedReader อ่าน character-input stream มัน buffer characters ใน buffer ขนาด default 8 KB เพื่อให้การอ่านมีประสิทธิภาพมากขึ้น หากคุณอยากอ่านไฟล์ทีละบรรทัด การใช้ BufferedReader เป็นตัวเลือกดี
BufferedReader มีประสิทธิภาพในการอ่านไฟล์ขนาดใหญ่
import java.io.*; public class FileReaderWithBufferedReader { public static void main(String[] args) throws IOException{ String file = "src/file.txt"; BufferedReader bufferedReader = new BufferedReader(new FileReader(file)); String curLine; while ((curLine = bufferedReader.readLine()) != null){ // process the line as required System.out.println(curLine); } bufferedReader.close(); } }
เมธอด readline() คืนค่า null เมื่อถึงท้ายไฟล์
หมายเหตุ: อย่าลืมปิดไฟล์เมื่ออ่านเสร็จ
การอ่านไฟล์ UTF-8 ใน Java ด้วย BufferedReader
เราสามารถใช้ class BufferedReader อ่านไฟล์ที่ encoded ด้วย UTF-8
คราวนี้ เราส่ง object InputStreamReader ตอนสร้าง instance BufferedReader
import java.io.*; public class EncodedFileReaderWithBufferedReader { public static void main(String[] args) throws IOException { String file = "src/fileUtf8.txt"; BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); String curLine; while ((curLine = bufferedReader.readLine()) != null){ // process the line as you require System.out.println(curLine); } } }
การใช้ Java Files Class อ่านไฟล์
Java Files class ที่ introduced ใน Java 7 ใน Java NIO ประกอบด้วย static methods เท่านั้นที่ operate บนไฟล์
ใช้ Files class คุณอ่านเนื้อหาเต็มไฟล์เข้า array ได้ ทำให้เหมาะสำหรับอ่านไฟล์เล็ก
มาดูวิธีใช้ Files class ในทั้งสองสถานการณ์
การอ่านไฟล์เล็กใน Java ด้วย Files Class
เมธอด readAllLines() ของ class Files อนุญาตอ่านเนื้อหาเต็มไฟล์ และเก็บแต่ละบรรทัดใน array เป็น strings
คุณสามารถใช้ class Path ได้ path ไปยังไฟล์ เนื่องจาก Files class รับ Path object ของไฟล์
import java.io.IOException; import java.nio.file.*; import java.util.*; public class SmallFileReaderWithFiles { public static void main(String[] args) throws IOException { String file = "src/file.txt"; Path path = Paths.get(file); List lines = Files.readAllLines(path); } }
คุณสามารถใช้ readAllBytes() ดึงข้อมูลในไฟล์เข้า byte array แทน string array
byte[] bytes = Files.readAllBytes(path);
การอ่านไฟล์ขนาดใหญ่ใน Java ด้วย Files Class
หากคุณอยากอ่านไฟล์ใหญ่ด้วย Files class ใช้เมธอด newBufferedReader() ได้ instance ของ BufferedReader class และอ่านไฟล์ทีละบรรทัดด้วย BufferedReader
import java.io.*; import java.nio.file.*; public class LargeFileReaderWithFiles { public static void main(String[] args) throws IOException { String file = "src/file.txt"; Path path = Paths.get(file); BufferedReader bufferedReader = Files.newBufferedReader(path); String curLine; while ((curLine = bufferedReader.readLine()) != null){ System.out.println(curLine); } bufferedReader.close(); } }
การอ่านไฟล์ด้วย Files.lines()
Java 8 เพิ่มเมธอดใหม่ให้ Files class อ่านไฟล์เต็มเข้า Stream ของ strings
import java.io.IOException; import java.nio.file.*; import java.util.stream.Stream; public class FileReaderWithFilesLines { public static void main(String[] args) throws IOException { String file = "src/file.txt"; Path path = Paths.get(file); Stream lines = Files.lines(path); lines.forEach(s -> System.out.println(s)); lines.close(); } }
การอ่าน Text Files ใน Java ด้วย Scanner
Class Scanner แบ่งเนื้อหาไฟล์เป็นส่วนๆ โดย delimiter ที่กำหนด และอ่านทีละส่วน วิธีนี้เหมาะที่สุดสำหรับอ่านเนื้อหาที่คั่นด้วย delimiter
ตัวอย่าง Scanner class เหมาะสำหรับอ่านรายการ integers คั่นด้วย whitespace หรือรายการ strings คั่นด้วย comma
Default delimiter ของ Scanner class คือ whitespace แต่คุณตั้ง delimiter เป็น character อื่นหรือ regular expression ได้ มี next methods หลากหลาย เช่น next(), nextInt(), nextLine(), nextByte() แปลงเนื้อหาเป็นชนิดต่างๆ
import java.io.IOException; import java.util.Scanner; import java.io.File; public class FileReaderWithScanner { public static void main(String[] args) throws IOException{ String file = "src/file.txt"; Scanner scanner = new Scanner(new File(file)); scanner.useDelimiter(" "); while(scanner.hasNext()){ String next = scanner.next(); System.out.println(next); } scanner.close(); } }
ในตัวอย่างข้างต้น เราตั้ง delimiter เป็น whitespace และใช้ next() method อ่านส่วนถัดไปของเนื้อหาที่คั่นด้วย whitespace
การอ่านไฟล์ทั้งไฟล์
คุณสามารถใช้ Scanner class อ่านไฟล์ทั้งไฟล์ครั้งเดียวโดยไม่ต้องลูป ต้องส่ง "\\Z" เป็น delimiter สำหรับนี้
scanner.useDelimiter("\\Z"); System.out.println(scanner.next()); scanner.close();
หมายเหตุ: Scanner class ไม่ synchronized ดังนั้นไม่ thread-safe
สรุป
เหมือนที่คุณเห็นในบทช่วยสอนนี้ Java มีหลายเมธอดให้เลือกตามลักษณะงานที่มีอยู่ เพื่ออ่าน text files คุณสามารถใช้ BufferedReader อ่านไฟล์ใหญ่ทีละบรรทัด
หากอยากอ่านไฟล์ที่เนื้อหาคั่นด้วย delimiter ใช้ Scanner class
และคุณสามารถใช้ Java NIO Files class อ่านทั้งไฟล์เล็กและใหญ่ได้