Java 如何按制表符和换行符拆分字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20637447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to split a string by tabs and newlines?
提问by Niklas
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\[email protected]\tpeterpassword\nBob\[email protected]\tbobbypassword\n...
Peter\[email protected]\tpeterpassword\nBob\[email protected]\tbobbypassword\n...
where \t
is a tab and \n
is a newline.
其中\t
是制表符,\n
是换行符。
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?
上面的代码会起作用吗?
采纳答案by Dodd10x
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.
我会String.split("\\n")
为每一行做一个。然后您就拥有了每个用户所需的所有信息。执行另一个操作String.split("\\t")
并使用结果数组构造您的对象。
From the Java Doc:
来自 Java 文档:
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.
StringTokenizer 是一个遗留类,出于兼容性原因保留,但不鼓励在新代码中使用它。建议任何寻求此功能的人改用 String 的 split 方法或 java.util.regex 包。
http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html
http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html