【问题标题】:java Scanner.hasNext always falsejava Scanner.hasNext 总是假的
【发布时间】:2017-06-19 22:36:43
【问题描述】:

在我的代码方法中,scanner.hasNext() 总是给出错误的结果。我在调试代码时理解它。有谁知道什么问题?我检查了文件。文件以字符串开头。

public class TextFileImplementor {
    public static void main (String [] args){
        System.out.println("Enter the name of file\n");
        Scanner scanner = new Scanner(System.in);
        File file = new File(scanner.nextLine());
        try {
            scanner = new Scanner(file);
            StringBuilder stringBuilder = new StringBuilder();
            while (scanner.hasNext()){
                stringBuilder.append(scanner.nextLine());
            }
            String [] strings = stringBuilder.toString().split("\\. ");
            File newFile = new File("new_" + file.getName());
            FileWriter fileWriter = new FileWriter(newFile, true);
            for (String string :
                    strings) {
                if (string.length()<141){
                    fileWriter.write(string + "\n");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}

【问题讨论】:

  • 可能文件是空的?
  • 如果您要致电scanner.nextLine(),请联系scanner.hasNextLine()。不过,可能不是问题。
  • @AndyTurner,改为scanner.hasNextLine()。问题没有解决。
  • 当我调试你的代码时,它读取文件中的行就好了。再看看你的输出代码和/或你的输入文件的内容。
  • @azurefrog ,现在我尝试使用不同的文件,有时它的工作。我猜它编码问题,我会尝试解决它。但数据不写入输出文件。我不明白为什么。

标签: java java.util.scanner


【解决方案1】:

问题已解决!我在输入文件的编码方面遇到了问题。我不得不添加

fileWriter.flush();
fileWriter.close();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-28
    • 2019-10-11
    • 2020-10-13
    • 1970-01-01
    • 2011-06-20
    • 1970-01-01
    相关资源
    最近更新 更多