I have a txt file like this:
5
1
3
6
9
I want to read them using java and store all of the numbers into a array.How do I do that? read them in as string and convert to arrray? (how to convert?) the file only contain ints.
I tried read them into a string and use this to convert
static public int[] strToA(String str)
{
int len = str.length();
int[] array = new int[len];
for (int i = 0; i < len; i++)
{
array[i] = Integer.parseInt(str.substring(i,i+1));
}
return array;
}
Scanner can help you read your file, and you can use a List
or something else to store the info.
After that, you can use this List
to convert your Array
.
public static Integer[] read2array(String filePath) throws IOException {
List<Integer> result = new ArrayList<Integer>();
RandomAccessFile randomAccessFile = new RandomAccessFile(filePath, "r");
String line = null;
while(null != (line = randomAccessFile.readLine())) {
result.add(new Integer(line));
}
randomAccessFile.close();
return result.toArray(new Integer[result.size()]);
}
Code would be something like this. This is untested code and may have Syntax errors.
Path file = "yourfile";
// open file
try (InputStream in = Files.newInputStream(file);
BufferedReader reader =
new BufferedReader(new InputStreamReader(in))) {
String line = null;
intArr = new int[10]; // bad code could fail if file has more than 10
int i = 0;
while ((line = reader.readLine()) != null) {
intArr[i++] = Integer.parseInt(line); // parse String to int
}
} catch (IOException x) {
System.err.println(x);
}
To use List instead of array change line
intArr = new int[10];
to
List intArr = new ArrayList();
Code would be something like
List intArr = new ArrayList();
while ((line = reader.readLine()) != null) {
intArr.add(Integer.parseInt(line)); // parse String to int
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.