我正在尝试从文本文件中读取特定字符以进行进一步处理。我试图读取的文件列为:
45721 Chris Jones D D C P H H C D
87946 Jack Aaron H H H D D H H H
43285 Ben Adams C F C D C C C P
24679 Chuck Doherty F F F P C C C F
57652 Dean Betts F C F C D P D H
67842 Britney Dowling D D F D D F D D
22548 Kennedy Blake P F P F P F P P
我想要阅读的特定字符是个人姓名后面的8个字符。我试图寻找解决方案,但我对java非常新,并且在理解逻辑方面存在问题,因此我们将非常感谢任何帮助。
答案 0 :(得分:2)
试用扫描仪课程,这对于这些东西来说非常棒
Scanner in = new Scanner(new File("./myfile.txt"));
while(in.hasNextLine()){
//read in a whole line
String line = in.nextLine();
//sanity check so we don't try to substring an empty string from an empty line at the end of the file.
if(line.length() == 0){
continue;
}
//15 chars from the end it 8 chars + 7 spaces
//We go back 16 though since the string index starts at 0, not 1.
line = line.subString(line.length()-16, line.length()-1);
//Now split the string based on any white spaces in between the chars spaces
String[] letters = line.split(" ");
//Now do something with your letters array
}
请注意,这假定您发布的格式非常严格。如果您想以不同的方式设置令牌,扫描仪也可以通过令牌读取令牌。 Check out the Scanner documentation
答案 1 :(得分:1)
如果该行的格式始终为#### FirstName LastName A1 A2 A3 A4 A5 A6 A7 A8
,则以下代码应该有效:
String line = "57363 Joy Ryder D D C P H H C D";
String[] cols = line.split("\\s+"); // split line by one or more whitespace chars
cols[0]
会有数字,cols[3]
到cols[10]
会有你想要的字母,A1到A8。
如果有中间名或没有姓氏,则索引会有所不同。