从java中的文本文件读取返回一些垃圾值

时间:2013-08-23 23:23:25

标签: java command-prompt

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

 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[]

如何避免这种情况?

3 个答案:

答案 0 :(得分:1)

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

那边你错过了i++;

但是我建议你使用这个结构:使用ArrayList而不是数组,因为这允许你有一个自调整大小的结构,而在while中使用方法ready();从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);
    }

答案 1 :(得分: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();
    }

答案 2 :(得分:0)

如果您使用的是eclipse IDE,请更改编码类型。转到编辑 - &gt;设置编码 - &gt;其他 - &GT; UTF-8