为什么我的文件在Java中变为空?

时间:2015-04-13 10:00:17

标签: java

尝试将迷宫中的文本文件读入Java。

import java.io.*;

public class Maze { 
    private char[][]mazeData;

    public static void main(String[] args) {
        Maze test = new Maze();
    }
    public Maze() { 
        BufferedReader reader = null;
        try {
            File f = new File("c://testing.txt");
            String line = null;
            int row = 0;
            reader = new BufferedReader(new FileReader(f));
            reader.mark((int)f.length());
            while ((line = reader.readLine()) != null) {
                 line = reader.readLine();
                 row++;
            }
            reader.reset();
            mazeData = new char[row][];
            row = 0;
            while ((line = reader.readLine()) != null) {
                mazeData[row++] = line.toCharArray();
            }
            int col=mazeData[0].length;
            for (int i=0; i < row; i++){
                for (int j=0; j < col; j++){
                    System.out.print(mazeData[i][j]);
                }
                System.out.println();
            }
            reader.close();

         } catch (IOException e) {
             System.out.println("INVALID FILE");
         }
            }

    }

我在另一个类中测试过,java可以在那里找到该文件,所以我不明白为什么异常会一直发生。

1 个答案:

答案 0 :(得分:2)

如果要打印catched异常,请阅读java.io.IOException: Mark invalid。由于标记已失效,因此会在reader.reset();处抛出此内容。

您可以通过

修复它
reader.mark((int)f.length() + 1);

无论如何,只需要知道行数就不需要处理两次文件。您可以将所有行读入List<String>并处理该数组中的行。

List<String> lines = Files.readAllLines(Paths.get("c:/testing.txt"),
    Charset.defaultCharset());

修改

一个精简的解决方案(基于您的代码)可能是。

public class Maze {

    private char[][] mazeData;

    public static void main(String[] args) {
        Maze test = new Maze();
    }

    public Maze() {
        try {
            List<String> lines = Files.readAllLines(Paths.get("c:/testing.txt"), Charset.defaultCharset());

            mazeData = new char[lines.size()][];
            for (int i = 0; i < lines.size(); i++) {
                mazeData[i] = lines.get(i).toCharArray();
            }
            int columns = mazeData[0].length;
            int rows = lines.size();
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < columns; j++) {
                    System.out.print(mazeData[i][j]);
                }
                System.out.println();
            }
        } catch (IOException ex) {
            System.out.println("failed: " + ex.getMessage());
        }
    }
}

保留其他一些评论:
- 避免在构造函数中进行I / O处理
- 将逻辑块中的代码分开(每个逻辑步骤一个方法),例如, initMazed(),printMaze()等