如何仅读取 5 行并按降序排列的文件。示例我有一个 my.log 文件,其中包含以下内容:
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
我想要的结果如下:
twelve
eleven
ten
nine
eight
我现在的代码是:
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class MainActivity extends Activity {
long sleepTime = 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String log = "/sdcard/my.log";
try {
Tail(log);
} catch (IOException e) {
e.printStackTrace();
}
}
public void Tail(String filename) throws IOException {
File checkfile = new File(filename);
if (checkfile.exists()) {
BufferedReader input = new BufferedReader(new FileReader(filename));
String currentLine = null;
while (true) {
if ((currentLine = input.readLine()) != null) {
Log.d("MyLog", currentLine);
continue;
}
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
input.close();
} else {
Log.d("MyLog", "File not found...");
}
}
}
但是这次结果是打印文件中的所有内容,结果不是按降序排序。所以现在结果如下:
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
谢谢。