Reputation: 19
I have a .txt file called capitals in my netbeans project folder which I need to create two parallel arrays for. The file contains 100 total entries, a state name on one line followed by a capital name of the next line. 50 states, 50 capitals.
I have googled and looked at examples on this site which contain the BufferedReader class but I am just not understanding the code provided to import the text file into 2 arrays and then call on them to be used in the program.
If somebody can help me with very simple explanations of code to use it would be much appreciated
Upvotes: 1
Views: 320
Reputation: 297
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
String fileName = "Capitals.txt";
int n = 50;
String[] capital = new String[n];
String[] state = new String[n];
try (Scanner inputStream = new Scanner(new FileInputStream(fileName))) {
for (int i = 0; i < n; i++) {
capital[i] = inputStream.nextLine();
state[i] = inputStream.nextLine();
}
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
return;
}
// do something with your arrays here
// ...
System.out.println(Arrays.toString(capital));
System.out.println(Arrays.toString(state));
}
}
Upvotes: 1
Reputation: 1126
Start by looking at FileReader
Here's a nice tutorial on how to read a file in Java.
Here are some helpfull Stackoverflow links
Upvotes: 1