假设我有一个名为"Keys.txt"
的txt文件:
Keys.txt:
Test 1
Test1 2
Test3 3
我想将字符串拆分成数组,我不知道该怎么做 我希望结果如此 像这样的数组:
Test
1
Test1
2
Test2
3
我已经启动了这个代码:
FileReader fr = new FileReader("Keys.txt");
BufferedReader br = new BufferedReader(fr);
String str = br.readLine();
br.close();
System.out.println(str);
答案 0 :(得分:2)
您可以按照以下步骤操作:
List.toArray()
)。例如:
List<String> list = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader("Keys.txt"))) {
String str;
while ((str = br.readLine()) != null) {
String[] token = str.split("\\s+");
list.add(token[0]);
list.add(token[1]);
}
}
String[] array = list.toArray(new String[list.size()]);
请注意,通过使用Java 8流和java.nio API(可从Java 7获得),您可以更简洁:
String[] array = Files.lines(Paths.get("Keys.txt"))
.flatMap(s -> Arrays.stream(s.split("\\s+"))
.collect(Collectors.toList())
.stream())
.toArray(s -> new String[s]);
答案 1 :(得分:2)
您可以将所有行存储在单个字符串上,用空格分隔,然后将其拆分为所需的数组。
FileReader fr = new FileReader("Keys.txt");
BufferedReader br = new BufferedReader(fr);
String str="", l="";
while((l=br.readLine())!=null) { //read lines until EOF
str += " " + l;
}
br.close();
System.out.println(str); // str would be like " Text 1 Text 2 Text 3"
String[] array = str.trim().split(" "); //splits by whitespace, omiting
// the first one (trimming it) to not have an empty string member
答案 2 :(得分:1)
String str = "Test 1 Test1 2 Test2 3";
String[] splited = str.split("\\s+");
答案 3 :(得分:1)
您可以使用String.split()
方法(在您的情况下是str.split("\\s+");
)。
它会将输入字符串拆分为一个或更多空白字符。由于Java API文档指出here:
\s
- 空白字符:[ \t\n\x0B\f\r]
X+
- X
,一次或多次。
答案 4 :(得分:0)
FileReader fr;
String temp = null;
List<String> wordsList = new ArrayList<>();
try {
fr = new FileReader("D://Keys.txt");
BufferedReader br = new BufferedReader(fr);
while ((temp = br.readLine()) != null) {
String[] words = temp.split("\\s+");
for (int i = 0; i < words.length; i++) {
wordsList.add(words[i]);
System.out.println(words[i]);
}
}
String[] words = wordsList.toArray(new String[wordsList.size()]);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
试试这个