218k views
3 votes
Write code that will copy the contents of the file into an array. You can assume that the file will only have 5 data values

1 Answer

5 votes

Answer:

Step-by-step explanation:

The following code is written in Java. It is a function that reads the file in the URL that is given in the parameter. It then places the file into a String and assumes that each element is separated by a space (" "). It then loops through that string adding each element into the created local ArrayList. Finally, It prints the contents of the ArrayList and returns the ArrayList.

public static ArrayList<String> toArray (String file) throws IOException {

ArrayList<String> myArr = new ArrayList<>();

BufferedReader reader = new BufferedReader(new FileReader(file));

String readFile = reader.readLine();

reader.close();

for (int x = 0; x < readFile.length(); x++) {

int start = 0;

if (readFile.charAt(x) == ' ') {

myArr.add(readFile.substring(start,x));

start = x + 1;

}

}

for (String x : myArr) {

System.out.println(x);

}

return myArr;

}

User Adiel
by
4.8k points