当前位置: 首页 > 知识库问答 >
问题:

从指定行。txt到字符串[]

华宇
2023-03-14

我想用中的行初始化字符串数组。txt文件。我写了这篇文章:

    public static void main(String[] args) {

        File file = new File("file.txt");
        int linesNumber = 0;
        String str;

        try {
            Scanner fileScan = new Scanner(file);

            //counting lines number in the file
            while(fileScan.hasNextLine()) {
                fileScan.nextLine();
                linesNumber++;
            }

            String[] strArray = new String[linesNumber];
            fileScan.reset();

            //assigning the array with lines from .txt file
            for (int i = 0; i < linesNumber; i++) {
                if (fileScan.hasNextLine()) {
                    strArray[i] = fileScan.nextLine();
                }
            }

            for (String s : strArray) {
                System.out.println(s);
            }

        } catch (FileNotFoundException ex) {
            System.out.println("Blad");
        }
    }

当我尝试读取最后一个for循环中的数组时,它会给我20行“null”。为什么会这样?这个txt文件只有20个单词,每个单词在另一行中。

共有2个答案

段干博涉
2023-03-14

你用fileScan.close()试过吗?

Scanner fileScan = new Scanner(file);

//counting lines number in the file
while(fileScan.hasNextLine()) {
     fileScan.nextLine();
     linesNumber++;
}
fileScan.close();
乜元魁
2023-03-14

这是重置的一种重复。nextLine()扫描仪

fileScan.reset();

并不像你想的那样。请留档阅读:https://www.geeksforgeeks.org/scanner-reset-method-in-java-with-examples/

 类似资料:
  • 我的配置文件有以下bean 我的班我的班是 为什么我会 无法将类型[java.lang.String]的值转换为属性“client”所需的类型[com.example.otherclasses.other]:找不到匹配的编辑器或转换策略

  • 本文向大家介绍Python 去除字符串中指定字符串,包括了Python 去除字符串中指定字符串的使用技巧和注意事项,需要的朋友参考一下 1、背景 最近的项目中,再次踩到Python字符串处理的坑,决定把此次解决方案记录一下,以勿踩坑。 2、遇到坑 原本字符串:大坪英利国际8号楼88-88号重庆汉乔科技有限公司大坪英利国际8号楼 去除最左边的字符串:大坪英利国际8号楼 预期结果:88-88号重庆汉乔

  • 我有一个varchar字段,存储类似的日期 我需要将这些值更改为

  • 问题内容: 这是我的代码: 我想在test.txt文件中找到一些单词 “ the” 。问题是当我找到第一个 “ the”时 ,我的程序停止寻找更多东西。 当诸如 “ then” 之类的单词被我的程序理解为 “ the” 一词时。 问题答案: 不区分大小写地使用Regexes,并使用单词边界查找“ the”的所有实例和变体。 无法区分 “ the” 和 “ then”, 因为它们均以“ the”开头

  • 问题内容: 我正在学习Go。 我的程序应该从stdin中读取数据,直到我输入一个单句点的行。 我应该如何修改for循环,以在输入单个点时停止程序? 我试图用for语句实现while循环,我的方法是否有问题,条件是否错误,还是ReadString弄乱了我的数据? 问题答案: … ReadString弄乱了我的数据吗? 不,不是。它正在阅读下一个。这意味着一行上只有一个点的行将具有数据或取决于操作系统

  • 没有用呢,中文的文件、文件夹仍会报错(malformed input off : 1, length : 1)。 这里都有注释的嘛,为什么会这样?