Java 按数字对文本文件的行进行排序,并按降序输出整行
我试图通过使用此代码将姓名和分数保存到文本文件中,从而建立一个高分系统Java 按数字对文本文件的行进行排序,并按降序输出整行,java,android,sorting,text-files,scoring,Java,Android,Sorting,Text Files,Scoring,我试图通过使用此代码将姓名和分数保存到文本文件中,从而建立一个高分系统 String text = name.getText().toString() + " " + score.getText().toString(); appendLog(text); } }); } public void appendLog(String text) { File logFile = new File("sdcard/logger.fi
String text = name.getText().toString() + " " + score.getText().toString();
appendLog(text);
}
});
}
public void appendLog(String text)
{
File logFile = new File("sdcard/logger.file");
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
有没有一种方法可以让我对每一行中的分数进行排序,并用相应的分数输出名称?有人能帮我怎么做吗?谢谢。让一行代表您的数据模型,即创建一个类似于
Entry
的类,该类的字段为name和score。然后,您将拥有这些对象的列表。编写一个自定义比较器,按分数降序排序。仅此而已=)正如@juvanis在他的文章中所说,创建一个类来表示每个记录,读取整个文件并将类对象生成一个列表,然后对列表进行排序,并按排序顺序将对象写入文件中
下面是一个用于表示记录的类的示例,该类由名称和分数组成
公共类记录{
个人智力得分;
私有字符串名称;
公共getScore(){
返回分数;
}
公共getName(){
返回名称;
}
公共记录(字符串名称、整数分数){
this.name=名称;
这个分数=分数;
}
}
为了对名称和分数文件进行排序,根据分数(我想您希望将记录从最高分数排序到最低分数),使用以下方法:
public void sortFile () {
// Reference to the file
File file = new File ( "sdcard/logger.file" );
// Check if the file exists
if ( ! file.exists () ) {
// File does not exists
return;
}
// Check if the file can be read
if ( ! file.canRead () ) {
// Cannot read file
return;
}
BufferedReader bufferedReader = null;
// The separator between your name and score
final String SEPARATOR = " ";
// A list to host all the records from the file
List < Record > records = new ArrayList < Record > ();
try {
bufferedReader = new BufferedReader ( new FileReader ( file ) );
String line = null;
// Read the file line by line
while ( ( line = bufferedReader.readLine () ) != null ) {
// Skip if the line is empty
if ( line.isEmpty () )
continue;
// Retrieve the separator index in the line
int separatorIndex = line.lastIndexOf ( SEPARATOR );
if ( separatorIndex == -1 ) {
// Separator not found, file is corrupted
bufferedReader.close ();
return;
}
// Create a record from this line. It is alright if the name contains spaces, because the last space is taking into account
records.add ( new Record ( line.substring ( 0 , separatorIndex ) , Integer.parseInt ( line.substring ( separatorIndex + 1 , line.length () ) ) ) );
}
} catch ( IOException exception ) {
// Reading error
} catch ( NumberFormatException exception ) {
// Corrupted file (score is not a number)
} finally {
try {
if ( bufferedReader != null )
bufferedReader.close ();
} catch ( IOException exception ) {
// Unable to close reader
}
}
bufferedReader = null;
// Check if there are at least two records ( no need to sort if there are no records or just one)
if ( records.size () < 2 )
return;
// Sort the records
Collections.sort ( records , new Comparator < Record > () {
@Override
public int compare ( Record record1 , Record record2 ) {
// Sort the records from the highest score to the lowest
return record1.getScore () - record2.getScore ();
}
} );
// Replace old file content with the new sorted one
BufferedWriter bufferedWriter = null;
try {
bufferedWriter = new BufferedWriter ( new FileWriter ( file , false ) ); // Do not append, replace content instead
for ( Record record : records ) {
bufferedWriter.append ( record.getName () + SEPARATOR + record.getScore () );
bufferedWriter.newLine ();
}
bufferedWriter.flush ();
bufferedWriter.close ();
} catch ( IOException exception ) {
// Writing error
} finally {
try {
if ( bufferedWriter != null )
bufferedWriter.close ();
} catch ( IOException exception ) {
// Unable to close writer
}
}
bufferedWriter = null;
// You can output the records, here they are displayed in the log
for ( int i = 0 ; i < records.size () ; i ++ )
Log.d ( "Record number : " + i , "Name : \"" + records.get ( i ).getName () + "\" , Score : " + records.get ( i ).getScore () );
}
public void排序文件(){
//对文件的引用
File File=新文件(“sdcard/logger.File”);
//检查文件是否存在
如果(!file.exists()){
//文件不存在
返回;
}
//检查文件是否可以读取
如果(!file.canRead()){
//无法读取文件
返回;
}
BufferedReader BufferedReader=null;
//你的名字和分数之间的分隔符
最终字符串分隔符=”;
//存放文件中所有记录的列表
Listrecords=newarraylist();
试一试{
bufferedReader=新bufferedReader(新文件读取器(文件));
字符串行=null;
//逐行读取文件
而((line=bufferedReader.readLine())!=null){
//如果行为空,则跳过
if(line.isEmpty())
继续;
//检索行中的分隔符索引
int separatorIndex=line.lastIndexOf(分隔符);
如果(分隔索引==-1){
//未找到分隔符,文件已损坏
bufferedReader.close();
返回;
}
//从这一行创建一个记录。如果名称中包含空格就可以了,因为最后一个空格是考虑在内的
records.add(新记录(line.substring(0,separatorIndex),Integer.parseInt(line.substring(separatorIndex+1,line.length()));
}
}捕获(IOException异常){
//读取错误
}捕获(NumberFormatException异常){
//损坏的文件(分数不是数字)
}最后{
试一试{
if(bufferedReader!=null)
bufferedReader.close();
}捕获(IOException异常){
//无法关闭读卡器
}
}
bufferedReader=null;
//检查是否至少有两条记录(如果没有记录或只有一条记录,则无需排序)
if(records.size()<2)
返回;
//对记录进行排序
Collections.sort(记录,新比较器(){
@凌驾
公共整数比较(记录记录1,记录记录2){
//将记录从最高分数排序到最低分数
返回record1.getScore()-record2.getScore();
}
} );
//用新排序的内容替换旧文件内容
BufferedWriter BufferedWriter=null;
试一试{
bufferedWriter=new bufferedWriter(new FileWriter(file,false));//不要追加,而是替换内容
用于(记录:记录){
bufferedWriter.append(record.getName()+分隔符+record.getScore());
bufferedWriter.newLine();
}
bufferedWriter.flush();
bufferedWriter.close();
}捕获(IOException异常){
//书写错误
}最后{
试一试{
if(bufferedWriter!=null)
bufferedWriter.close();
}捕获(IOException异常){
//无法关闭写入程序
}
}
bufferedWriter=null;
//您可以输出记录,它们将显示在日志中
for(inti=0;i
如果你有什么不明白的,请告诉我。
尝试一下,如果它按照您的预期运行良好,请让我了解最新情况。您能给我举个例子让我更好地理解它吗?很抱歉,我不熟悉java。谢谢你,朱瓦尼斯