0

我正在通过命令提示符执行某些命令并将值存储在文本文件中。

 wmic logicaldisk where drivetype=3 get deviceid > drive.txt

现在我想从我的 java 文件中读取存储在文本文件中的字符串。当我尝试这样做时:

            try {
            File file = new File("drive.txt");
            FileReader reader = new FileReader(file);
            BufferedReader in = new BufferedReader(reader);
            int i=0;
            while ((string[i] = in.readLine()) != null) {
                System.out.println(string[i]);
                    ++i;

            }
            in.close();
          } catch (IOException e) {
            e.printStackTrace();
          }

我得到如下输出:

 ÿþD[]E[]V[]I[]C[]E[]

如何避免这种情况?

4

3 回答 3

1
  while ((string[i] = in.readLine()) != null) {
                System.out.println(string[2]);
            }

在那里你错过了i++;

但是我建议你使用这个结构:使用 aArrayList而不是数组,因为这允许你有一个自调整大小的结构,也可以在 while 中使用方法 ready(); from 是BufferedRead为了从文档中检查结尾,最后只是为了显示 String ArrayList 中的元素。

ArrayList<String> string = new ArrayList<String>();
    try {

        File file = new File("drive.txt");
        BufferedReader entrada;
        entrada = new BufferedReader(new FileReader(file));

        entrada.readLine();
        while (entrada.ready()) {

            string.add(entrada.readLine());
        }
        entrada.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    for (String elements : string) {
        System.out.println(elements);
    }
于 2013-08-23T23:26:33.597 回答
0

为什么这里需要一个字符串数组?数组的大小可能不对?只需使用字符串而不是数组。我试过了,对我来说效果很好:

    try {
        String string;
        File file = new File("drive.txt");
        FileReader reader = new FileReader(file);
        BufferedReader in = new BufferedReader(reader);
        int i = 0;
        while ((string = in.readLine()) != null) {
            System.out.println(string);
            ++i;

        }
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
于 2013-08-24T00:56:03.230 回答
0

如果您使用的是 Eclipse IDE,请更改编码类型。转到编辑->设置编码->其他->UTF-8。

于 2017-12-06T12:18:04.497 回答