In java if i want to assign an array values from a second file, how do I code that? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

In java if i want to assign an array values from a second file, how do I code that?

Let's call it String [] Names; and a method is supposed to read a file called List.names and assign each new line to a new array element. so if List.names content is Valerie Sable Wade Sherry the array should be String [] Names = {"Valerie","Sable","Wade","Sherry"} How should the code look to do this?

13th Jul 2017, 6:19 PM
Wade Grimm
Wade Grimm - avatar
2 Answers
+ 2
It would be better to use a List instead of an array as an array is not dynamic. A list data type works in a similar way to an array but can have items added and removed dynamically. List<String> names = new ArrayList<String>(); BufferedReader reader = null; try { File file = new File("names.txt"); reader = new FileReader(file); String line = null; while((line = reader.readLine()) != null) { names.add(line); } catch (IOException e) { e.printStackTrace(); } finally { reader.close(); } To retrieve an item from the list use names.get(index);
13th Jul 2017, 7:51 PM
Hassie
Hassie - avatar
+ 1
ok, I'll need to look into it more to understand it myself as I just started learning Java and am planning to rewrite a program I wrote in c++ win32 api. And thank you. Edit 3 minutes later: Irony is I just got to the part talking about ArrayList. Edit 30 minutes later: ok just took a second look and understand most of it.
16th Jul 2017, 12:09 AM
Wade Grimm
Wade Grimm - avatar