2

I am reading a text file into an arraylist and getting them by line but I want to split each line and put in a two dimensional array however String [][] array=lines.split(","); gives me an error.

File file=new File("text/file1.txt");
ArrayList<String> lines= (ArrayList<String>) FileUtils.readLines(file);
String [][] array=lines.split(",");
2
  • String [] array=lines.split(","); it will always return 1-dimension array. Commented Dec 10, 2015 at 7:35
  • 1
    I think this duplicate question stackoverflow.com/questions/10043209/… Commented Dec 10, 2015 at 7:39

2 Answers 2

4

You must split each element of the List separately, since split operates on a String and returns a 1-dimensional String array :

File file=new File("text/file1.txt");
ArrayList<String> lines= (ArrayList<String>) FileUtils.readLines(file);
String [][] array=new String[lines.size()][];
for (int i=0;i<lines.size();i++)
    array[i]=lines.get(i).split(",");
Sign up to request clarification or add additional context in comments.

Comments

0

split() returns [] not [][]. try this :

File file=new File("text/file1.txt");
List<String> lines= (ArrayList<String>) FileUtils.readLines(file);
String [][] array= new String[lines.size()][];
int index = 0;
for (String line : lines) {
    array[index] = line.split(",");
    index++;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.