【问题标题】:How can I read user defined objects from a file?如何从文件中读取用户定义的对象?
【发布时间】:2020-03-23 07:13:52
【问题描述】:

我正在使用 BufferedReader 从文件中读取 Word 对象,但事实证明 BufferedReader 被设计为只能读取字符串,而不是用户定义的对象。

在这种情况下,Word 对象是一个字符串,只是没有定义为字符串

换句话说,如何将 str2[i] 从 String 转换为 Word 对象以便将其入队?

这是因为 enqueue 方法接受 Word 对象。

    public static void main(String[] args) {

    WordPriorityQueue x = new WordPriorityQueue();
    File file = new File("file goes here");
    BufferedReader br = new BufferedReader(new FileReader(file));

    String st;
    while((st = br.readLine()) != null) {
            String str1 = br.readLine();
            String str2[] = str1.split(" ", 500);
            int i = 0;
            while(str2[i] != null) {
                //How can I convert the string str2[i] to a Word object?
                x.enqueue(str2[i]);  //Doesn't work for Strings
                i++;
            }
        }
    }

【问题讨论】:

  • 您没有使用BufferedReader。我不确定什么是“Word”对象,但要读取二进制数据,您使用InputStream,要读取Java 序列化对象,您可以使用ObjectInputStream 包装它们。但是请edit这个问题并解释一下Word对象是什么。
  • 或者你只需​​要从一个字符串构造一个单词。像new Word(string) 这样的东西。但由于我们不知道 Word 类是什么,所以很难说。

标签: java arrays oop object bufferedreader


【解决方案1】:

我认为您没有使用 javax.speech.Word 对象。我想 Word 是你的课程。

为了创建一个新对象,Java 提供了构造函数。

定义

Java中的构造函数是一种特殊的方法,用于初始化 对象。构造函数在类的对象被调用时被调用 已创建。

因此,在您的代码中,您必须使用构造函数为每个项目创建一个 Word 对象。

public static void main(String[] args) throws IOException {

    //List that contains all words
    List<Word> wordsList = new ArrayList<>();

    //Create the scanner
    File file = new File("file goes here");
    Scanner sc = new Scanner(file);    

    while( sc.hasNextLine() ) {
        String[] lineSplitted = sc.nextLine().split(" "); //add 500 as limit

        for (i=0; i<lineSplitted.length; i++) {
            //Call constructor
            wordsList.add(new Word(lineSplitted[i])                
        }
    }

    sc.close()
 }

在您的 Word 类中,添加一个构造函数,该构造函数作为参数需要一个字符串。

public class Word {

  private String word;

  public Word(String word) {
    this.word = word;
  }

  //Other methods, getter, setter, etc...
}

最后,您将拥有 java.util.ListWord 个对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-19
    • 2020-03-17
    • 1970-01-01
    • 2013-04-29
    • 2011-09-26
    • 2015-12-30
    相关资源
    最近更新 更多