【问题标题】:Why can't I read Strings from a file?为什么我不能从文件中读取字符串?
【发布时间】:2016-10-08 21:34:14
【问题描述】:

该代码应该从文件中读取字符串数组,然后将其打印出来。我不确定代码有什么问题。

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class program2 {

    public static void main(String[] args) throws IOException {
        //PriorityQueue<String> q = new PriorityQueue<String>();
        //file that contains strings
        File file = new File("infix.txt");
        Scanner scnf = new Scanner(file);
        // array count
        int arycnt = 0; 
        // gets the count of the array in the file
        while(scnf.hasNextLine()){
            arycnt++;
            scnf.next();
        }
        // creates array
        String[] letter = new String[arycnt];
        //reads in array from  file
        Scanner scnf2 = new Scanner(file);
        for(int i = 0; i<arycnt ;i++){
            letter[i] = scnf2.next();
        }
        // suppose to print all of the array
        for (int i = 0;i < letter.length;i++){
            System.out.println(letter[i]);
        }

    }

}

【问题讨论】:

  • 您永远不会关闭两个 Scanner 对象,因此您正在泄漏资源。我还建议使用ArrayList&lt;String&gt; 而不是String[],这样您就不必阅读该文件两次。

标签: java string file-io java.util.scanner


【解决方案1】:

您混淆了nextLinenext。将您的hasNextLine() 替换为hasNext(),您应该没问题。

【讨论】:

  • 或者将next()替换为nextLine(),这取决于文件中的“字符串”是各占一行,还是用空格分隔的“标记”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多