首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Java-12读取文本文件

用Java-12读取文本文件
EN

Stack Overflow用户
提问于 2014-03-03 00:45:46
回答 2查看 344关注 0票数 0

想一想一个文本文件,比如:

代码语言:javascript
复制
line1 ->5
line2 ->A 10
line3 ->B 15
line4 ->C 25
line5 ->D 5
line6 ->E 30

'5‘是{a,b,c,d,e}的数。如何将这些变量保存在两个数组中,如:

代码语言:javascript
复制
Array1[5] = {A,B,C,D,E}
Array2[5] = {10,15,25,5,30}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-03-03 01:12:54

代码语言:javascript
复制
// 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]);
}

或者更容易..。

代码语言:javascript
复制
// 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();
}
票数 0
EN

Stack Overflow用户

发布于 2014-03-03 00:57:42

// x=文件的内容

代码语言:javascript
复制
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();
}

在将它们放到数组中之后,它将转到下一行。应该以你想要的方式读你的文件。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22135813

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档