【问题标题】:Java-Files: get specific index from text fileJava-Files:从文本文件中获取特定索引
【发布时间】:2021-01-12 14:21:41
【问题描述】:

我有以下目录server/auth/usernames.txt,我想读取所有行并找到名为clientusername的字符串的特定索引

我有以下代码

File dirFile = new File("auth/");
String clientUsername ="john";
int indexUsername = Files.readAllLines(Paths.get(dirFile.getAbsolutePath() + "usernames.txt")).indexOf(clientUsername);

但这给了我server/auth/usernames.txt 的完整路径。我只想得到auth/usernames.txt。如何做到这一点?

【问题讨论】:

    标签: java file path


    【解决方案1】:

    dirFile.getAbsolutePath() 更改为dirFile.toPath()

    【讨论】:

      【解决方案2】:
      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?
          
      }
      

      在我完全编造的用户名文件中只使用与 Eminem 相关的用户名运行它(MC Hammer 得到 -1 ......显然我们仍然无法触及这个。

      run:
      1
      0
      2
      -1
      BUILD SUCCESSFUL (total time: 0 seconds)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多