简体   繁体   English

在java中将文本文件复制到二维字符数组中

[英]Copying a text file into a 2D char array in java

I'm working on reading a text file that contains an 5x6 character big ascii image.我正在阅读一个包含 5x6 字符大 ascii 图像的文本文件。 Here's what i've done so far:这是我到目前为止所做的:

  ...    
  Scanner fileReader = null;
  try{
     File file = new File(fileName);
     fileReader = new Scanner(file);
     int offset = 0;

     char [][] pic = new char[5][6];

     while (fileReader.hasNextLine()){
        for (int u = 0; u < row; u++){
           for (int i = 0; i < col; i++){
              String line = fileReader.nextLine();
              pic[u][i] = line.charAt(offset++);
           }
        }
        return pic;
     }
     fileReader.close();
  }
  catch(Exception e){
     System.out.println(e.getMessage());
  }...

This gives me a "no line found" message.这给了我一个“找不到线路”的消息。 I'm wondering if the scanner i use to ask the user the name of the file is a part of the problem.我想知道我用来询问用户文件名的扫描仪是否是问题的一部分。 Here's what that looks like:这是它的样子:

  System.out.println("Hello! I load files.");
  System.out.println("Please, enter file name:");
  Scanner reader = new Scanner(System.in);
  String fileName = reader.nextLine();

I've tried to close the reader after but it didn't change anything.之后我试图关闭阅读器,但它没有改变任何东西。 Any help is much appreciated.任何帮助深表感谢。

Several things :几件事:

First, you are attempting to read a line for each index of your array (that is row*col times).首先,您试图为数组的每个索引读取一行(即row*col时间)。

Second, you should only read a line by row.其次,您应该只逐行阅读。

You may replace your whole while loop with this :你可以用这个替换你的整个while循环:

    for (int u = 0; u < row && fileReader.hasNextLine(); u++) {

        String line = fileReader.nextLine();

        for (int i = 0; i < col; i++) {

            pic[u][i] = line.charAt(offset++);
        }

        offset = 0;
    }
    return pic;

Also , you probably want to reset the value of offset after each processed "row".此外,您可能希望在每个处理过的“行”之后重置offset的值。

Scanner fileReader = new Scanner (new File("file.txt"));
int i = 0;
char[][] pic = new char[5][];
while (fileReader.hasNextLine()){
    String line = fileReader.nextLine();
    pic[i] = line.toCharArray();
    i++;
}
fileReader.close();

I tried it with seuqnce and worked:我用 seuqnce 尝试过并工作:

 Scanner fileReader = new Scanner(System.in);
    System.out.println(fileReader.nextLine());
    fileReader.close();

    fileReader = new Scanner (new File("file.txt"));
    int i = 0;
    char[][] pic = new char[5][];
    while (fileReader.hasNextLine()){
        String line = fileReader.nextLine();
        pic[i] = line.toCharArray();
        System.out.println(line);
        i++;
    }
    fileReader .close();

output:输出:

sadsadd sadsadd伤心难过

sadasdasdasdsad sadasdasdsadsa sadasdasdsadsadsa dAS dASd萨达斯达斯达萨达萨达萨达萨达萨达萨达达萨达萨达达萨达达萨达

Process finished with exit code 0进程以退出代码 0 结束

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM