Java-将第一行存储到字符串用户中,将第二行存储在字符串通行中,删除这两行



我在这样做时遇到了麻烦,我尝试了很多方法,无法实现它。

基本上,我的项目中有一个称为用户的文本文件。该文本文件包含以下行:

  1. 用户1
  2. Pass1
  3. 用户2
  4. pass2
  5. 用户3
  6. pass3

我正在尝试将文本文件的第一行存储到一个名为用户的字符串中,然后将第二行存储到一个名为Pass的字符串中,然后从文件中删除两行。这样,我将只能使用这两个字符串,而不是一直复制/粘贴用户名/密码。

任何人都可以帮忙吗?

谢谢!

尝试此代码。这使用了简单的逻辑,它读取文件的所有内容并写回内容。

import java.io.*;
public class UserPass {
    public static void main(String[] args) {
        FileReader fr;
        BufferedReader br;
        PrintWriter pw;
        String[] pass;
        String[] user;
        String tmp;
        int FileContentCount;
        // Number Of users used for initialize the string arrays .
        int noOfUsers = 3;
        pass = new String[noOfUsers];
        user = new String[noOfUsers];
        // Reading User Name From File 
        String UserFileName = "userdetails.txt";
        try {
            fr = new FileReader(UserFileName);
            br = new BufferedReader(fr);
            // 
             FileContentCount= 0;
            while ((tmp = br.readLine()) != null) {
                user[FileContentCount] = tmp;
                tmp = br.readLine();
                pass[FileContentCount] = tmp;
                FileContentCount++;
            }
            br.close();
            fr.close();
            // Printing First Username  and Pass This canbe used for Your use
            System.out.println(user[0] + " : " + pass[0]);
            // Deleting File Contents Actualy writing without those contents.
           pw = new PrintWriter(UserFileName);
            int count = 1;// Avoiding the First User Details
            while (count < FileContentCount) {
                    pw.write(user[count] + "n");
                    pw.write(pass[count] + "n");
                    count++;
            }
            pw.flush();
            pw.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

尝试以下:(

最新更新