java Scanner.hasNext始终为false

时间:2017-06-19 22:36:44

标签: java java.util.scanner

在我的代码方法中,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();
        }


    }
}

1 个答案:

答案 0 :(得分:0)

问题解决了!我输入文件的编码有问题。我不得不添加

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