我正在尝试从文本文件中读取特定字符以进行存储以供进一步处理。我试图读取的文件布局如下:
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 非常陌生,并且在理解逻辑方面存在问题,因此我们将不胜感激任何帮助。
最佳答案
尝试 Scanner 类,它非常适合这个东西
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
}
请注意,这假设您发布的格式非常严格。如果您想以稍微不同的方式进行设置,扫描仪还可以逐个读取 token 。 Check out the Scanner documentation .
关于java - 从文件中读取特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26279003/