Java从文件中读取数据的六种方法
在Java应用程序中,从文件中读取数据是一个常见的操作。这篇文章将为大家介绍Java读取文件的六种方法,帮助大家学习如何读取文件数据。
方法1:使用 FileInputStream
FileInputStream fileInputStream = null;
try {
File file = new File("file.txt");
fileInputStream = new FileInputStream(file);
int content;
while ((content = fileInputStream.read()) != -1) {
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fileInputStream != null) {
fileInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
方法2:使用 BufferedReader 和 FileReader
BufferedReader bufferedReader = null;
try {
File file = new File("file.txt");
FileReader fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
方法3:使用 RandomAccessFile
RandomAccessFile randomAccessFile = null;
try {
randomAccessFile = new RandomAccessFile("file.txt", "r");
String line = null;
while ((line = randomAccessFile.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (randomAccessFile != null) {
randomAccessFile.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
方法4:使用 Scanner
Scanner scanner = null;
try {
scanner = new Scanner(new File("file.txt"));
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (scanner != null) {
scanner.close();
}
}
方法5:使用 Files 类的 readAllBytes 方法
try {
byte[] bytes = Files.readAllBytes(Paths.get("file.txt"));
System.out.println(new String(bytes));
} catch (IOException e) {
e.printStackTrace();
}
方法6:使用 Files 类的 readAllLines 方法
try {
List<String> lines = Files.readAllLines(Paths.get("file.txt"));
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
以上就是Java从文件中读取数据的六种方法,我们可以根据需求选择方法进行文件读取。
下面是一个使用BufferedReader的示例:
public static void main(String[] args) {
BufferedReader bufferedReader = null;
try {
File file = new File("file.txt");
FileReader fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
下面是一个使用Scanner的示例:
public static void main(String[] args) {
Scanner scanner = null;
try {
scanner = new Scanner(new File("file.txt"));
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (scanner != null) {
scanner.close();
}
}
}
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:java从文件中读取数据的六种方法 - Python技术站