遇到困难,创造一个程序,读取和Java中的.txt文件写的2D阵列/ [英] Having difficulties creating a program that reading and writing 2D arrays to/from .txt files in Java

查看:102
本文介绍了遇到困难,创造一个程序,读取和Java中的.txt文件写的2D阵列/的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关家庭作业,我需要创建一个类,可以读取和写入文件的字节数组/。我已经成功地创建了一个可以读写CSV和文字,但我有一些困难,当涉及到数组类。

当我运行'readByte的方法(见下文),我不明白编译器错误,相反,我不能得到的文件的内容进行打印。相反,控制台只显示文件读取,这表明它已经成功地处理了嵌套循环。我已经研究了各种资源,但我无法找到解决方案。我相信这是一个简单的错误的地方,我如何能解决这将是极大的AP preciated任何建议。

我试图读取该文件的内容也低于

第二个问题(我认为这将是最好的放在一个职位这两个问题),在我的'writeByte的方法(用户输入值到一个二维数组,然后在一个.txt文件打印),让我进入两个值之前,我后续的错误消息:

 异常线程mainjava.lang.ArrayIndexOutOfBoundsException:4
在com.gc01.FileManager.ByteManager.writeByte(ByteManager.java:93)
在com.gc01.FileManager.ByteManager.main(ByteManager.java:111)

我相信它的东西与为循环如何收集用户输入的做,但我不能工作了如何纠正它。理想情况下,文件将类似于文件由readByte'方法读取。

我这个理解很长的问题,但我遇到了一个砖墙和所有帮助将大大AP preciated!


文件内容(由制表符分隔)


  1 10
2月11日
3月12日
4月13日


 公共类ByteManager {公共字符串getByteFile(){
    扫描仪SC =新的扫描仪(System.in);
    的System.out.println(请输入所选择的TXT文件的文件目录?);
    的System.out.println(例如:/Users/UserName/Downloads/FileName.txt);
    ///Users/ReeceAkhtar/Desktop/FileName.txt
    最后字符串文件名= sc.nextLine();
    的System.out.println(有多少列在文件中?);
    最终诠释列= sc.nextInt();
    的System.out.println(有多少行是该文件中?);
    最终诠释行= sc.nextInt();
    返回文件名;
    }公共无效readByte(最后字符串的文件名,INT行,诠释列){BR的BufferedReader = NULL;的String []线;
字符串splitBy =\\ t的;
INT [] []数据=新的INT [行] [列];
尝试{
    BR =新的BufferedReader(新的FileReader(文件名));
        的for(int i = 0; I<行;我++){
            。行= br.toString()分(splitBy);
            //数据[I] [0] =的Integer.parseInt(行[I]);
            对于(INT J = 0; J<列; J ++){
                数据[I] [J] =的Integer.parseInt(行[J]);
                的System.out.println(数据[I] [J]);
            }
        }
    }赶上(FileNotFoundException异常五){
        e.printStackTrace();
    }赶上(IOException异常五){
        e.printStackTrace();
    } {最后
        如果(BR!= NULL){
        尝试{
        br.close();
    }赶上(IOException异常五){
        e.printStackTrace();
    }
        }
    }
    的System.out.println(*****文件读取*****);
}
公共字符串chooseFileOutput(){
    扫描仪SC =新的扫描仪(System.in);
    的System.out.println(请输入该选择的文件的输出文件目录);
    的System.out.println(例如:/Users/UserName/Downloads/FileName.txt);
    ///Users/ReeceAkhtar/Desktop/GeoIPCountryWhois.csv
    最后弦乐fileNameOUT = sc.nextLine();
    返回fileNameOUT;
    }公共无效writeByte(最后弦乐fileNameOUT){
    扫描仪输入=新的扫描仪(System.in);
    FileOutput createData =新FileOutput(fileNameOUT);
    的System.out.println(有多少行?);
    INT rowsOut = input.nextInt();
    的System.out.println(有多少列?);
    INT columnsOut = input.nextInt();
    的System.out.println(请输入数据。);        INT newDataR = 0;
        INT newDataC = 0;
        INT [] []数据=新的INT [rowsOut] [columnsOut];
        的for(int i = 0; I< rowsOut;我++){
            createData.writeInteger(newDataR = input.nextInt());
            System.out.print(\\ t的);
            对于(INT J = 0; J< columnsOut;我++){
                createData.writeInteger(newDataC = input.nextInt());
                数据[I] [J] =数据[newDataR] [newDataC];
                System.out.print(\\ t的);
            }
        }
        createData.close();}公共静态无效的主要(字串[] args){
    扫描仪在=新的扫描仪(System.in);
    最后ByteManager对象=新ByteManager();    的System.out.println(1读取文件,2写文件);
    字符串选择= in.nextLine();
    如果(1.equals(选择)){
        object.readByte(object.getByteFile(),0,0);
    }否则如果(2.equals(选择)){
        object.writeByte(object.chooseFileOutput());
    }其他{
        的System.out.println(再见!);
        System.exit(0);
    }
}
}


解决方案

有关你的第一个问题(有关无法读取):

方法,下面一行:

  object.readByte(object.getByteFile(),0,0);

有被从文本文件中读取的行和列的数量提供0和0。该方法 getByteFile()并提示输入行数和列的用户,但它不返回这个数量,所以没有任何与这些数字。您必须提示行数和列数的用户,并把这些作为 readByte 的第二个和第三个参数的方法在

此外,在一般情况下,我不知道为什么你懒得建立在双方你的 readByte INT [] []数据 $ C>和 writeByte 方法。它们是无效的方法,这样你就不会返回 INT [] [] ,或做任何有意义的吧。你打算以后使用此对象?

For a homework assignment, I need to create a class that that can read and write Byte arrays to/from a file. I have successfully created classes that can read and write CSV and text, however I am having some difficulty, when it comes to arrays.

When I run the 'readByte' method (see below) I do not get compiler errors , instead, I can not get the contents of the file to print. Instead the console just displays "File Read", demonstrating that it has successfully processed the nested for loop. I have studied various resources yet I can not find the solution. I am sure it is a simple mistake somewhere, any advice on how I can resolve this will be greatly appreciated.

The contents of the file I am trying to read is also below.

A second question (I thought it would be best to put both questions in one post), in my 'writeByte' method (the user enters values into a 2D array which is then printed in a .txt file), allows me to enter two values before I get the follow error message:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at com.gc01.FileManager.ByteManager.writeByte(ByteManager.java:93)
at com.gc01.FileManager.ByteManager.main(ByteManager.java:111)

I am sure its something to do with how the for the loop collects the user input, but I can't work out how to correct it. Ideally the file would look similar to the file being read by the 'readByte' method.

I understand this a long question, but I have run into a brick wall and all help would be greatly appreciated!


File Contents (separated by tab)


1     10
2     11
3     12
4     13


public class ByteManager {

public String getByteFile(){
    Scanner sc = new Scanner (System.in);
    System.out.println("Please enter the file directory of the chosen txt file?");
    System.out.println("For Example: /Users/UserName/Downloads/FileName.txt");
    ///Users/ReeceAkhtar/Desktop/FileName.txt
    final String fileName = sc.nextLine();
    System.out.println("How many columns are in the file?");
    final int columns = sc.nextInt();
    System.out.println("How many rows are in the file?");
    final int rows = sc.nextInt();
    return fileName;
    }



public void readByte(final String fileName, int rows,int columns){

BufferedReader br = null;

String[] line;
String splitBy =  "\t";
int [][] data = new int[rows] [columns];


try {
    br = new BufferedReader(new FileReader(fileName));  
        for (int i = 0; i < rows; i++){
            line = br.toString().split(splitBy);
            //data[i] [0] = Integer.parseInt(line[i]);
            for (int j = 0; j < columns; j++){
                data[i] [j] = Integer.parseInt(line[j]);
                System.out.println(data[i][j]);
            }
        }       
    } catch (FileNotFoundException e){
        e.printStackTrace();
    } catch (IOException e) {   
        e.printStackTrace();  
    } finally {  
        if (br != null) {  
        try {  
        br.close();  
    } catch (IOException e) {  
        e.printStackTrace();  
    }
        }
    }
    System.out.println("*****File Read*****");
}


public String chooseFileOutput(){
    Scanner sc = new Scanner (System.in);
    System.out.println("Please enter the file directory for the output of the chosen file");
    System.out.println("For Example: /Users/UserName/Downloads/FileName.txt");
    ///Users/ReeceAkhtar/Desktop/GeoIPCountryWhois.csv
    final String fileNameOUT = sc.nextLine();
    return fileNameOUT;
    }

public void writeByte(final String fileNameOUT){
    Scanner input = new Scanner (System.in);
    FileOutput createData = new FileOutput (fileNameOUT);
    System.out.println("How many rows?");
    int rowsOut = input.nextInt();
    System.out.println("How many columns?");
    int columnsOut = input.nextInt();


    System.out.println("Please enter data.");

        int newDataR = 0;
        int newDataC = 0;
        int [] [] data = new int [rowsOut] [columnsOut];    


        for (int i = 0; i < rowsOut; i++){
            createData.writeInteger(newDataR = input.nextInt());
            System.out.print("\t");
            for (int j = 0; j < columnsOut; i++){
                createData.writeInteger(newDataC = input.nextInt());
                data[i] [j] = data[newDataR] [newDataC];
                System.out.print("\t");
            } 
        }   
        createData.close();

}

public static void main(String[] args) {
    Scanner in = new Scanner (System.in);
    final ByteManager object = new ByteManager ();

    System.out.println("1 for Read File, 2 for Write file");
    String choice = in.nextLine();
    if("1".equals(choice)){
        object.readByte(object.getByteFile(), 0, 0);
    } else if ("2".equals(choice)){
        object.writeByte(object.chooseFileOutput());
    } else{
        System.out.println("Goodbye!");
        System.exit(0);
    }
}
}

解决方案

For your first question (about being unable to read):

In the main method, the following line:

object.readByte(object.getByteFile(), 0, 0);

Provides 0 and 0 for the number of rows and columns to be read from the text file. The method getByteFile() does prompt the user for a number of rows and columns, however it does not return this amount and does nothing with those numbers. You must prompt the user for the number of rows and columns and put those as the second and third arguments of the readByte method in main.

Also, in general, I wonder why you bother to create the object int[][] data in both your readByte and writeByte methods. They are void methods, so you don't return the int[][], or do anything meaningful with it. Do you intend to use this object later?

这篇关于遇到困难,创造一个程序,读取和Java中的.txt文件写的2D阵列/的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆