簡體   English   中英

我需要一個文件讀取器來逐行讀取文本文件並將其格式化為Java

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

我有一個文本文件,格式如下:

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

我需要創建一個arrayList對象,該對象存儲玩家的姓名( Han Solo )及其得分( 1000 )作為屬性。 我希望能夠通過逐行讀取文件並拆分字符串以獲取所需的屬性來制作此arrayList。 我嘗試使用Scanner對象,但沒有成功。 在此方面的任何幫助將不勝感激,謝謝。

您可以創建一個Class Call player playerNamescore將是屬性。

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

然后您可以創建一個List

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

現在,您可以嘗試完成任務。

此外,您可以從文件中讀取內容,並用: 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);
   }     

您可以擁有一個像這樣的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.
}

您可以解析包含如下數據的文件:

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.

如果您有對象:

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;
    }

}

創建一個從文件讀取的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());
        }
    }
}

輸出將是:

Han Solo 1000哈里100羅恩10尤達0

假設您有一個名為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();
                }
        }

對於小文件(小於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;
    }

}

}

讀取文件並將其轉換為可用於結果的字符串和拆分函數。

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