Convert string representation of array back to int

2020-05-09 22:56发布

just started programming with Java. If I have an array as follows stored in a .txt file:

[10, 22, 30, 55, 10, 20, 19]

How do I convert it back to a normal int[] array to be used within the code?

I need to be able to store it plainly in a txt file like this so I can make changes to it manually. I've used BufferedReader to read the array. How can I put the read array into an int[] array?

int[] field;    
try {
    String line;
    br = new BufferedReader(new FileReader(gameFilePath));
    while((line = br.readLine()) != null) { // Read the first line and assume it is the stored array
        field = line;
        System.out.println("-------------------------------------------------------------------");
        System.out.println(line);
    }
} catch(IOException e) {
    e.printStackTrace(); 
}

标签: java arrays
2条回答
我只想做你的唯一
2楼-- · 2020-05-09 23:44

What you're talking about doing is parsing the text. A simple way to implement this yourself for a beginner if you know the structure of the text is to hard code the rules for reading in a function and use Scanner.

I'm on my phone so I'll put details later but there's tons of info on how to do that if I'm not in time

查看更多
够拽才男人
3楼-- · 2020-05-09 23:56

So if your line is

[10, 22, 30, 55, 10, 20, 19]

then you can do

line = line.replace ("[", "");
line = line.replace ("]", "");

then you can use String.split

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

then for each val you can use

intVal [x] = Integer.valueOf (val[x].trim ());
查看更多
登录 后发表回答