Java IO是Java编程语言的核心库之一,它通过提供一组类和接口,使我们能够进行文件和数据流的操作。在Java IO中,文件读取是常见的操作之一。下面我们将介绍Java IO文件操作从文件读取数据的六种方法。
示例代码:
import java.io.*;
import java.util.Scanner;
public class ReadFileExample1 {
public static void main(String[] args) throws FileNotFoundException {
FileInputStream inputStream = new FileInputStream("test.txt");
Scanner scanner = new Scanner(inputStream);
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
scanner.close();
}
}
示例代码:
import java.io.*;
public class ReadFileExample2 {
public static void main(String[] args) throws IOException {
FileReader reader = new FileReader("test.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line = null;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
}
}
示例代码:
import java.io.*;
import java.util.Scanner;
public class ReadFileExample3 {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("test.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
scanner.close();
}
}
示例代码:
import java.io.*;
public class ReadFileExample4 {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileInputStream inputStream = new FileInputStream("test.txt");
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = null;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
}
}
示例代码:
import java.io.*;
import java.util.Scanner;
public class ReadFileExample5 {
public static void main(String[] args) throws FileNotFoundException {
FileInputStream inputStream = new FileInputStream("test.txt");
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
Scanner scanner = new Scanner(bufferedInputStream);
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
scanner.close();
}
}
示例代码:
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class ReadFileExample6 {
public static void main(String[] args) throws IOException {
Stream<String> stream = Files.lines(Paths.get("test.txt"));
stream.forEach(System.out::println);
stream.close();
}
}
以上就是Java IO文件操作从文件读取数据的六种方法的详细攻略,每种方法都有对应的示例代码,可以根据具体需求选择使用。
本文链接:http://task.lmcjl.com/news/13175.html