簡體   English   中英

逐字符地從txt文件中讀取文本(用戶:傳遞)

[英]reading text (user:pass) from txt file character by character

我試圖從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();
}

如果使用JAVA:8和8+,你可以在Files上使用stream - 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...
    }

或者使用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處理。 上面的代碼只是為了向您展示邏輯。

我認為你不需要額外的循環

public static void main(String[] args) throws IOException {
        BufferedReader reader;
        try {
            reader = new BufferedReader(new FileReader(
                    "path/to/file"));
            String line = reader.readLine();
            while (line != null) {
                System.out.println(line);
                // read next line
                line = reader.readLine();
                if (line.contains(":")) {
                    String user = line.split(":")[0];
                    String pass = line.split(":")[1];
                    System.out.println("User is " + user + "Password is " + pass);
                }            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

版畫

user1:pass1
User is user2Password is pass2
user2:pass2
User is user3Password is pass3
user3:pass3

這是一個詳細的實施 -

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Stream;

public class ReadFileAsStream {

    public static void main(String... arguments) {
        CredentialsParser parser;
        try {
            parser = new CredentialsParser("c:/temp/credtest.txt");
            Credential[] credentials = parser.getCredentials();
            for (Credential credential : credentials) {
                System.out.println(String.format("%s : %s", credential.getUsername(), credential.getPassword()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//Parser for the credentials file format
class CredentialsParser {
    private Set<Credential> credentials = new HashSet<>();
    String filename = null;

    public CredentialsParser() {
        super();
    }

    public CredentialsParser(String filename) throws IOException {
        super();
        setFilename(filename);

        if (getFilename() != null) {
            parseCredentialsFile();
        }
    }

    public Credential[] getCredentials() {
        return credentials.toArray(new Credential[credentials.size()]);
    }

    // method to add credentials
    public void addCredential(String entry) {
        if (entry.indexOf(':') > -1) {
            String[] values = entry.split(":");
            credentials.add(new Credential(values[0], values[1]));
        }
    }

    public String getFilename() {
        return filename;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }

    protected void parseCredentialsFile() throws IOException {
        // read file into stream, try-with-resources
        try (Stream<String> stream = Files.lines(Paths.get(filename))) {
            stream.forEach(this::addCredential);
        }
    }
}

// Value holder for each credential entry
class Credential {
    private String username = null;
    private String password = null;

    public Credential() {
        super();
    }

    public Credential(String username, String password) {
        super();
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

請將您的代碼修改為:

使用split方法讓您的工作變得輕松:)

public class Example {

    public static void main(String[] args) {
        BufferedReader reader;
        try {
            reader = new BufferedReader(new FileReader("F://test.txt"));
            String line = reader.readLine();
            while (line != null) {
                String[] lineParts = line.split(":");
                System.out.println("user : " + lineParts[0]);
                System.out.println("password : " + lineParts[1]);
                line = reader.readLine();
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

在test.txt中:

user1:pass1
user2:pass2
user3:pass3

輸出:

user : user1
password : pass1
user : user2
password : pass2
user : user3
password : pass3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM