[英]Java-Files: get specific index from text file
I have the following directory server/auth/usernames.txt
and i want to read all lines and find a specific index of the string called clientusername
我有以下目录
server/auth/usernames.txt
,我想读取所有行并找到名为clientusername
的字符串的特定索引
I have the following piece of code我有以下一段代码
File dirFile = new File("auth/");
String clientUsername ="john";
int indexUsername = Files.readAllLines(Paths.get(dirFile.getAbsolutePath() + "usernames.txt")).indexOf(clientUsername);
but this gives me the full path of server/auth/usernames.txt
.但这给了我
server/auth/usernames.txt
的完整路径。 I want only to get auth/usernames.txt
.我只想得到
auth/usernames.txt
。 How to achieve this?如何做到这一点?
Change dirFile.getAbsolutePath()
to dirFile.toPath()
将
dirFile.getAbsolutePath()
更改为dirFile.toPath()
public static void main(String[] args) {
File f = new File("path-to-your-file-on-your-system!");
System.out.println(getLineNumber("SlimShady", f));
System.out.println(getLineNumber("Eminem", f));
System.out.println(getLineNumber("MomsSpaghetti", f));
System.out.println(getLineNumber("doodoodoodoo....doooooooooo...dooooooo...can't touch this!", f));
}
private static int getLineNumber(String userName, File usernameFile) {
boolean found = false;
int lineCount = -1;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(usernameFile)))) {
String line;
while ((line = reader.readLine()) != null && !found) {
++lineCount; // increment and get (start at 0)
found = line.trim().equals(userName); // found it?
}
} catch (IOException ex) {
Logger.getLogger(TestMain.class.getName()).log(Level.SEVERE, null, ex);
}
if (!found) {
// we didn't find it... return -1 (an impossible valid value) to handle that scenario.
lineCount = -1;
}
return lineCount; // found it, what line?
}
And running it with only Eminem-related usernames in my totally made-up usernames file (we get a -1 for MC Hammer... apparently we still can't touch this.并且在我完全编造的用户名文件中只使用与 Eminem 相关的用户名运行它(我们得到 MC Hammer 的 -1 ......显然我们仍然无法触及它。
run:
1
0
2
-1
BUILD SUCCESSFUL (total time: 0 seconds)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.