0
想一想等的文本文件:读取文本文件中的Java-12
line1 ->5
line2 ->A 10
line3 ->B 15
line4 ->C 25
line5 ->D 5
line6 ->E 30
'5' 是{A,B,C,d,E}的数目。
Array1[5] = {A,B,C,D,E}
Array2[5] = {10,15,25,5,30}
想一想等的文本文件:读取文本文件中的Java-12
line1 ->5
line2 ->A 10
line3 ->B 15
line4 ->C 25
line5 ->D 5
line6 ->E 30
'5' 是{A,B,C,d,E}的数目。
Array1[5] = {A,B,C,D,E}
Array2[5] = {10,15,25,5,30}
// read all lines in the file into a list
List<String> lines = Files.readAllLines(Paths.get("filename"), Charset.defaultCharset());
// determine the length of the arrays based on the first line
int length = Integer.parseInt(lines.remove(0));
// first column
String[] col1 = new String[length];
// second column
int [] col2 = new int[length];
// now for every remaining row, add to each column
for(int i = 0; i < length; i++){
String [] pair = lines.remove(0).split(" ");
col1[i] = pair[0];
col2[i] = Integer.parseInt(pair[1]);
}
或者更简单...
// create a scanner of the file
Scanner scan = new Scanner(new File("filename"));
// read the first token as an int to know array length
int length = scan.nextInt();
String [] col1 = new String[length];
int [] col2 = new int[length];
// assuming valid data, loop through each row
for(int i = 0; i < length; i++){
col1[i] = scan.next();
col2[i] = scan.nextInt();
}
// x =从您的文件
while(x.hasNext) {
String a = x.next(); // This will get the first bit (e.g A, B, C, etc)
String b = x.next(); // This will get the last bit (e.g 10, 15, 25, etc)
// now just put them in the array
// for every extra bit of data you have on a line you just add another String y = x.next();
}
它把他们的阵列将转到下一行后的内容:我怎样才能在两个数组喜欢持有这些变量。 这应该按照你想要的方式读取你的文件。
什么是Java的12? – fge
听起来像你想要http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html – OSborn
打开文件,读取第一行并将其存储在变量中初始化您的数组。循环播放其余的行,将它们分割为单个空格字符,将前半部分存储在第一个数组中,将后半部分存储在第二个数组中。完成。 –