java - 阅读文本(用户 :pass) from txt file character by character

标签 java file text

我正在尝试从 Java 中的 .txt 文件中读取用户名和密码。 文件格式如下:

user1:pass1
user2:pass2
user3:pass3

我的代码无法正确读取密码,有什么提示吗? 编辑:还缺少最后一个密码,因为最后一个 \n 丢失了,有什么方法可以修复它而不是向 txt 文件添加额外的换行符?

try {
    FileReader fileReader = new FileReader(filename);
    BufferedReader bufferedReader = new BufferedReader(fileReader);

    int c;
    String user = "";
    String pass = "";
    char helper = 0;

    while(( c = bufferedReader.read()) != -1 ) {
        System.out.println((char)c);
        if((char)c == '\n') {
            ftpServer.addUser(user, pass);
            //System.out.printf("%s", pass);
            user = "";
            pass = "";
            helper = 0;
        } else {
            if ((char) c == ':') {
                helper = ':';
            }
            if (helper == 0) {
                user += (char) c;
            }
            if (helper == ':') {
                if ((char) c != ':')
                    pass += (char) c;
            }
        }
    }
    bufferedReader.close();
}

最佳答案

If using JAVA: 8 and 8+ you could use stream on Files - java.nio.files

Path path = Paths.get(filename);
    try (Stream<String> lines = Files.lines(path)) {
        lines.forEach(s -> {
            if (s.contains(":")) {
                String[] line = s.split(":");
                String userName = line[0];
                String pass = line[1];
                System.out.println("User name: " + userName + " password: " + pass);
            }
        });
    } catch (IOException ex) {
        // do something or re-throw...
    }

Or use BufferedReader

BufferedReader reader;
    try {
        reader = new BufferedReader(new FileReader("/Users/kants/test.txt"));
        String lineInFile = reader.readLine();
        while (lineInFile != null) {
            if (lineInFile.contains(":")) {
                String[] line = lineInFile.split(":");
                String userName = line[0];
                String pass = line[1];
                System.out.println("User name: " + userName + " password: " + pass);
            }
            lineInFile = reader.readLine();
        }
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

注意:您必须进一步添加 null 检查和 try-catch 处理。上面的代码只是为了向您展示逻辑。

关于java - 阅读文本(用户 :pass) from txt file character by character,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55110174/

相关文章:

java - 通过增加数量值将相同的商品添加到购物车,而不是将商品添加到新行

java - 在提供的示例的上下文中,使用synchronized(this) 将方法划分为多个部分是否有助于提高性能?

android - 何时使用 gdx.files.internal 以及何时使用相对路径?

c - 重复文件查找算法的建议(使用 C)

python - 自动登录脚本需要使用存储在txt文件中的多个帐户登录

CSS 和将文本放置在图像旁边

html - 如何在连字符 (-) 等特殊字符后打断单词

java - 使用 log4j 创建不同的日志文件

java - ResultSet.getTimestamp ("date") 与 ResultSet.getTimestamp ("date", Calendar.getInstance(tz))

c# - 如何将文本文件中的文本插入到 C# 中的标签控件中