简体   繁体   中英

Reading file into 2D array?

So i'm trying to read from a text file by bytes, and then read char of it. but i'm trying to insert it into a 2D array , which is ankoshh.

Any help is appreciated :)

public class SteamOutputToFile 
{


public static void main(String [] args)
    {
        int row;
        int col;
        String [][] ankoshh = new String[row][col];
        try{
        InputStream inputstream = new FileInputStream("E:\\testing.txt");

    int data = inputstream.read();
    while(data != -1) {
      //do something with data...
      System.out.print((char)data);

      data = inputstream.read();
    }
    }
    catch (IOException ioexception){
        System.out.println("File input error occured!");
        ioexception.printStackTrace();
    }
    for (int i=0; i<ankoshh.length;i++)
    {
        for (int j=0; j<ankoshh[i].length;j++)
        {
            ankoshh[row][col] = (char)data[i];
        }

Apache common-io greatly help you to do that, it is not necessary to use FileInputStream.

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.io.FileUtils;

public class Test
{
   public static void main(String [] args) throws IOException
   {
      File file = new File (args[0]);
      List<String> lines = FileUtils.readLines (file);

      String[][]ankoshh = new String [lines.size ()][];

      int line_index=0;
      for (String line:lines)
      {
         String[] caracters = line.split("(?!^)");
         ankoshh[line_index++] = caracters;
      }
   }
}

If file are really big you can also use line iterator:

LineIterator it=FileUtils.lineIterator (file);
while (it.hasNext ())
...

Hope this helps.

Cheers,

Fred

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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