简体   繁体   中英

How to split a string by tabs and newlines?

I got a tab-delimited file that I want to split by tabs and by newlines where a tab represents the delimiter between fields and a newline represents a new object that should be created. The file can look like this:

Peter\\tpeter@example.com\\tpeterpassword\\nBob\\tbob@bobby.com\\tbobbypassword\\n...

where \\t is a tab and \\n is a newline.

I want to enable uploading this file to my program that creates a new user for every line in the file with the fields on the line. But how can I use two tokens - both tab and newline? My code would look something like the following:

String everything = "";
BufferedReader br = null;
try {
    br = new BufferedReader(new InputStreamReader(file.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();

    while (line != null) {

       //now create object according to the string
       StringTokenizer st = new StringTokenizer(line , "\t");    
       String name = st.nextToken();
       String email = st.nextToken();
       String password = st.nextToken();
       User.createNewUser(name, email, password);

        sb.append(line);
        sb.append('\n');
        line = br.readLine();
    }
    everything = sb.toString();
    br.close();
} catch (IOException e) {
    e.printStackTrace();
}
System.out.println("Everything: " + everything);

Would code like the above work?

I would do a String.split("\\\\n") for each line. Then you have all the information you need for each user. Do another String.split("\\\\t") and construct your object using the resulting array.

From the Java Doc:

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM