如何在 java 中读取文件时获取索引值



我写了一段代码从文件中读取值,

public class Test { 
public static void main(String[] args) throws Exception { 
// pass the path to the file as a parameter 
FileReader fr = new FileReader("/home/workspace_ag7_tmv/Message Router/environments/wb/conf/subscriber_content_restriction.conf"); 
int i; 
while ((i=fr.read()) != -1) {
System.out.print((char) i); 
} 
}
}

在我的文件中,我传递了这些值: PRE|00000000110000200000049U POS|10000000110000200000049U

我能够使用上面的代码段获取这些值,现在我想获取第 4 个索引值。你能帮我怎么做吗?

您可以将字符添加到 ArrayList,然后在第 4 个索引处获取元素。

int i;
List<Character> charList = new ArrayList<>();    
while ((i=fr.read()) != -1) 
charList.add((char) i);
System.out.print((char) i); 
}
// to get char at index 4
char a = charList.get(4);

阅读您的其他问题后: 如果要获取"|"后面的值的索引,则可以将列表转换为字符串并获取indexOf "|"并向该索引添加1。

像这样:

int i;
List<Character> charList = new ArrayList<>();    
while ((i=fr.read()) != -1) 
charList.add((char) i);
System.out.print((char) i); 
}
String str= charList.stream()             
.map(String::valueOf)   
.collect(Collectors.joining()); 
int firstPos = str.indexOf('|');
System.out.println(str.charAt(firstPos+1));
int secondPos = str.indexOf('|', firstPos+1);
System.out.println(str.charAt(secondPos+1));
/***********************************
* a bit of ugly code               *
* you read all lines in a list
* you cycle the list and tokenizeit*
* you get the PRE digit char in i  *
* and the POS digit in i2          * 
***********************************/
public class GetAllLines {
StringTokenizer sToken;
String s;
public static void main(String[] args) {
try {
List<String> lines = Files.readAllLines(Paths.get("/home/workspace_ag7_tmv/Message Router/environments/wb/conf/subscriber_content_restriction.conf"));
for (String line : Lines) {
sToken = new StringTokenizer(line, "|");
while (sToken.hasMoreElements()) {
//you can get after PRE 1st digit
s=sToken.nextElement().nextElement().toString();//the 1st getElementgets the PRE the 2nd gets all string up to POS
int i = Integer.parseInt(s.getSymbol(0).charAt(0)); //you get the next to PRE
s=sToken.nextElement().toString();//the 3rd getElement gets all string after POS
int i2 = Integer.parseInt(s.getSymbol(0).charAt(0)); //you get the next digit after POS
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

最新更新