简体   繁体   English

我需要一个文件读取器来逐行读取文本文件并将其格式化为Java

[英]I need to get a file reader to read a text file line by line and format them in Java

I have a text file, formatted as follows: 我有一个文本文件,格式如下:

Han Solo:1000
Harry:100
Ron:10
Yoda:0

I need to make an arrayList of objects which store the player's name ( Han Solo ) and their score ( 1000 ) as attributes. 我需要创建一个arrayList对象,该对象存储玩家的姓名( Han Solo )及其得分( 1000 )作为属性。 I would like to be able to make this arrayList by reading the file line by line and splitting the string in order to get the desired attributes. 我希望能够通过逐行读取文件并拆分字符串以获取所需的属性来制作此arrayList。 I tried using a Scanner object, but didn't get far. 我尝试使用Scanner对象,但没有成功。 Any help on this would be greatly appreciated, thanks. 在此方面的任何帮助将不胜感激,谢谢。

You can create a Class call player . 您可以创建一个Class Call player playerName and score will be the attributes. playerNamescore将是属性。

public class Player {
  private String playerName;
  private String score;
  // getters and setters
}

Then you can create a List 然后您可以创建一个List

List<Player> playerList=new ArrayList<>();

Now you can try to do your task. 现在,您可以尝试完成任务。

Additionally, you can read from file and split each line by : and put first part as playerName and second part as score . 此外,您可以从文件中读取内容,并用: split每一行,并将第一部分作为playerName ,第二部分作为score

   List<Player> list=new ArrayList<>();
   while (scanner.hasNextLine()){
       String line=scanner.nextLine();
       Player player=new Player();
       player.setPlayerName(line.split(":")[0]);
       player.setScore(line.split(":")[1]);
       list.add(player);
   }     

You can have a Player class like this:- 您可以拥有一个像这样的Player类:

class Player { // Class which holds the player data
    private String name;
    private int score;

    public Player(String name, int score) {
        this.name = name;
        this.score = score;
    }

    // Getters & Setters
    // Overrride toString()  - I did this. Its optional though.
}

and you can parse your file which contains the data like this:- 您可以解析包含如下数据的文件:

List<Player> players = new ArrayList<Player>();
try {
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))); // I used BufferedReader instead of a Scanner
    String line = null;
    while ((line = br.readLine()) != null) {
        String[] values = line.split(":"); // Split on ":"
        players.add(new Player(values[0], Integer.parseInt(values[1]))); // Create a new Player object with the values extract and add it to the list
    }
} catch (IOException ioe) {
    // Exception Handling
}
System.out.println(players); // Just printing the list. toString() method of Player class is called.

If you have Object: 如果您有对象:

public class User
{
    private String name;
    private int score;

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public int getScore()
    {
        return score;
    }

    public void setScore(int score)
    {
        this.score = score;
    }

}

Make an Reader class that reads from the file : 创建一个从文件读取的Reader类:

public class Reader
{
    public static void main(String[] args)
    {
        List<User> list = new ArrayList<User>();
        File file = new File("test.txt");
        BufferedReader reader = null;
        try
        {
            reader = new BufferedReader(new FileReader(file));
            String line;
            while ((line = reader.readLine()) != null)
            {
                String[] splitedString = line.split(":");
                User user = new User();
                user.setName(splitedString[0]);
                user.setScore(Integer.parseInt(splitedString[1]));
                list.add(user);
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (reader != null)
            {
                try
                {
                    reader.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }

        for (User user : list)
        {
            System.out.println(user.getName()+" "+user.getScore());
        }
    }
}

The output will be : 输出将是:

Han Solo 1000 Harry 100 Ron 10 Yoda 0 Han Solo 1000哈里100罗恩10尤达0

Let's assume you have a class called Player that comprises two data members - name of type String and score of type int. 假设您有一个名为Player的类,该类包含两个数据成员-String类型的名称和int类型的score

List<Player> players=new ArrayList<Player>();
        BufferedReader br=null;
        try{
            br=new BufferedReader(new FileReader("filename"));
            String record;
            String arr[];
            while((record=br.readLine())!=null){
                arr=record.split(":");
                //Player instantiated through two-argument constructor
                players.add(new Player(arr[0], Integer.parseInt(arr[1])));
            }
        } catch (FileNotFoundException e) {             
            e.printStackTrace();
        } catch (IOException e) {               
            e.printStackTrace();
        }
        finally{
            if(br!=null)
                try {
                    br.close();
                } catch (IOException e1) {                      
                    e1.printStackTrace();
                }
        }

For small files (less than 8kb), you can use this 对于小文件(小于8kb),您可以使用此文件

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class NameScoreReader {

List<Player> readFile(final String fileName) throws IOException
{
    final List<Player> retval = new ArrayList<Player>();

    final Path path = Paths.get(fileName);
    final List<String> source = Files.readAllLines(path, StandardCharsets.UTF_8);
    for (final String line : source) {
        final String[] array = line.split(":");
        if (array.length == 2) {
            retval.add(new Player(array[0], Integer.parseInt(array[1])));
        } else {
            System.out.println("Invalid format: " + array);
        }
    }
    return retval;
}


class Player {

    protected Player(final String pName, final int pScore) {
        super();
        this.name = pName;
        this.score = pScore;
    }

    private String name;

    private int score;

    public String getName()
    {
        return this.name;
    }
    public void setName(final String name)
    {
        this.name = name;
    }

    public int getScore()
    {
        return this.score;
    }
    public void setScore(final int score)
    {
        this.score = score;
    }

}

} }

Read the file and convert it to string and split function you can apply for the result. 读取文件并将其转换为可用于结果的字符串和拆分函数。

public static String getStringFromFile(String fileName) {
        BufferedReader reader;
        String str = "";
        try {
            reader = new BufferedReader(new FileReader(fileName));
            String line = null;
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
                stringBuilder.append("\n");
            }
                str = stringBuilder.toString();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }

    public static void main(String[] args) {
        String stringFromText = getStringFromFile("C:/DBMT/data.txt");
        //Split and other logic goes here
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM