Java可以使用以下幾種方法讀取文件內容:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFileExample {
public static void main(String[] args) {
try {
File file = new File("path/to/file.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileExample {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("path/to/file.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class ReadFileExample {
public static void main(String[] args) {
try {
Path path = Paths.get("path/to/file.txt");
List<String> lines = Files.readAllLines(path);
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意:上述代碼中的"path/to/file.txt"需要替換為實際的文件路徑。