Jump to content

Java Read file and import into 2D Array?

Arcapse

Hello, me again xD

 

In Java, how would I read from a text file and save it as a 2D array?

 

The text file contains the player's initials and score as shown below:

 

gDOGh0G.jpg

 

Cheers & Best Regards,

Arcapse

Link to comment
Share on other sites

Link to post
Share on other sites

1 hour ago, Arcapse said:

Hello, me again xD

 

In Java, how would I read from a text file and save it as a 2D array?

 

The text file contains the player's initials and score as shown below:

 

gDOGh0G.jpg

 

You could read the file line by line and split at a comma.

in that loop you could add it to a dictionary/map?

or perhaps make an object.

 

Link to comment
Share on other sites

Link to post
Share on other sites

1 hour ago, Arcapse said:

Hello, me again xD

 

In Java, how would I read from a text file and save it as a 2D array?

 

The text file contains the player's initials and score as shown below:

 

gDOGh0G.jpg

 

It's generally frowned upon to use raw arrays, and this sort of thing would be better suited for a HashMap (the Dictionary mentioned above has been since marked obsolete. This is assuming that a players initials would only appear once in the file. Here's how to do what was requested:

Map<String, Integer> playerScores = new HashMap<String, Integer>();
String filePath = "/path/to/your/file.txt";
  
try {
	BufferedReader readFromFile = new BufferedReader(new FileReader(filePath));
	String rawInput;
    while ((rawInput = readFromFile.readLine()) != null) {
    	String[] splitInput = rawInput.split(",");
  		if (splitInput.length != 2) {
  			System.out.println("Invalid data entry read: " + rawInput);
    		continue;
  		}
        try {
        	playerScores.put(splitInput[0], Integer.parseInt(splitInput[1]));
  		} catch (Exception ex) {
            System.out.println("Invalid data entry read (value is not an integer): " + splitInput[1]);
  		}
  	}
    readFromFile.close();
} catch (IOException ex) {
    System.out.println("IOException caught while reading file: " + ex.getMessage());
}

//Print all items in map
for (Map.Entry<String, Integer> entry : playerScores.entrySet()) {
    String playerInitials = entry.getKey();
    Integer playerScore = entry.getValue();
    System.out.println("Player Initials: " + playerInitials + ", Player Score: " + playerScore);
}

//Or, access single persons scores:
Integer tylersScore = playerScores.get("TLA");
System.out.println("Tylers score: "  + tylersScore);

 

Link to comment
Share on other sites

Link to post
Share on other sites

Use a reader to read each line

split each line by ","

throw the split into an array list

copy array list to a 2d array

Quote

//Use a reader to read each line

BufferedReader bufferedReader = new BufferedReader(new FileReader(inputFile));

String line;

ArralyList<String> list = new ArrayList<String>();

while ((line = bufferedReader.readLine()) != null) {

    //split each line by ","

    String[] row = line.split(",");

    //throw the split into an array list

    list.add(row);

}

//copy array list to a 2d array

String[][] 2dArray = String[list.size()][2];

list.toArray(2dArray);

 

             ☼

ψ ︿_____︿_ψ_   

Link to comment
Share on other sites

Link to post
Share on other sites

import java.io.FileReader;
import java.util.List;
import java.util.ArrayList;
import java.io.BufferedReader;

public class PlayerReader {

	public static void main(String...args) {
		List<PlayerEntry> data = parse("player.data");
		
		
		
		//print all data
		data.forEach(System.out::println);
		//as array
		//PlayerEntry[] arrayData = (PlayerEntry[]) data.toArray();
	}
	
	//parsing data from file
	public static List<PlayerEntry> parse(String srcFile) {
		final ArrayList<PlayerEntry> data = new ArrayList<>();
		String line = null;//contain current line
		int lineNum = 1;//line number
		try(final BufferedReader reader = new BufferedReader(new FileReader(srcFile))) {
			while((line = reader.readLine()) != null) {//try read line from reader
				String[] split = line.split(",");
				data.add(
					new PlayerEntry(
						split[0],//initials
						Integer.parseInt(split[1].trim())//score
					)
				);
				lineNum++;
			}
		} catch(Exception e) {
			System.err.println("line parsing " + lineNum + " : " + line);
			e.printStackTrace();
		}
		return data;
	}
	
	public static class PlayerEntry {
		public final String initials;
		public final int score;
		public PlayerEntry(String initials, int score) {
			this.initials = initials;
			this.score = score;
		}
		@Override
		public String toString() {
			return initials + ", " + score;
		}
	}
}

 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×