fileReader = new FileReader(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
Scanner sc = new Scanner(fileReader);
String line = null;
while((sc.hasNextLine()&&(line=sc.nextLine())!=null)){
if(!sc.hasNextLine()){
System.out.println(line);
sc.close();
FileReader fileReader = null; try { fileReader = new FileReader(file); } catch (FileNotFoundException e) { e.printStackTrace(); } Scanner sc = new Scanner(fileReader); String line = nu...
public class Solution {
public static void main(String[] args)throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String name = reader.readLine();
FileR.
当我们在
读取
文件
的时候,通常都是从前向后
读取
,那如果要
读取
文件
的
最后
一行
内容,要如何操作呢?
顺序遍历
读取
,直到
文件
最后
一行
public static String readLastLineV0(File file) {
String lastLine = "";
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
String currentLine = "";
Scanner sc=new Scanner(new FileReader("D:\\text.txt"));
String line=null;
while((sc.hasNextLine()&&(line=sc.nextLine())!=null)){
if(!sc.hasNextLine())
System.out.println(line);
注意: 我们要
读取
的
文件
一定要存在,如果我们要
读取
的
文件
不存在,这个时候就会出现FileNotFoundexception
FileReader(字符输入流)
读取
数据的步骤:
首先我们要实例化一个File类的对象 --> 指明要操作的
文件
然后我们要提供具体的流对象(这里我们就是创建一个FileReader类的对象) --> 让这个流对象拿到我们的
文件
的操作权
这个时候我
1、首先在pom
文件
导入依赖
<!--在
Java
中,我们可以使用 Apache Commons IO 的 ReversedLinesFileReader 类
读取
文件
的
最后
几行。 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
可以使用
Java
中的BufferedReader和FileReader类来
读取
文件
,并通过调用readLine()
方法
来
读取
文件
的每
一行
。为了
读取
上
一行
,您可以使用mark()
方法
和reset()
方法
来在
读取
一行
后返回到上
一行
。
以下是一个示例代码:
import
java
.io.BufferedReader;
import
java
.io.FileReader;
import
java
.io.IOException;
public class ReadFile {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String currentLine, previousLine = null;
while ((currentLine = reader.readLine()) != null) {
if (previousLine != null) {
// 上
一行
的内容
System.out.println("Previous line: " + previousLine);
previousLine = currentLine;
reader.close();
} catch (IOException e) {
e.printStackTrace();
在此示例中,我们使用了一个变量previousLine来存储上
一行
的内容,并在
读取
当前行时打印出上
一行
的内容。