Reputation: 29
Lets assume I have a txt file called "Keys.txt"
:
Keys.txt:
Test 1
Test1 2
Test3 3
I want to split the strings into an array and I dont know how to do it I want that the result will be in array like this:
Test
1
Test1
2
Test2
3
I have this started code:
FileReader fr = new FileReader("Keys.txt");
BufferedReader br = new BufferedReader(fr);
String str = br.readLine();
br.close();
System.out.println(str);
Upvotes: 0
Views: 2527
Reputation: 368
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();
}
try this out
Upvotes: 0
Reputation: 131346
You can follow these steps :
List.toArray()
).For example :
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()]);
Note that by using Java 8 streams and the java.nio API (available from Java 7) you could be more concise :
String[] array = Files.lines(Paths.get("Keys.txt"))
.flatMap(s -> Arrays.stream(s.split("\\s+"))
.collect(Collectors.toList())
.stream())
.toArray(s -> new String[s]);
Upvotes: 2
Reputation: 70
You could store all the lines on a single string, separated by spaces, and then split it into your desired array.
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
Upvotes: 2
Reputation: 3609
You can use String.split()
method (in your case it's str.split("\\s+");
).
It will split input string on one or more whitespace characters. As Java API documentation states here:
\s
- A whitespace character: [ \t\n\x0B\f\r]
X+
- X
, one or more times.
Upvotes: 1
Reputation: 35
String str = "Test 1 Test1 2 Test2 3";
String[] splited = str.split("\\s+");
Upvotes: 1