I have a string array:
String[] word ={"atom","electron","oxyegn","explosion","combustion","flask","laser","molecule","ion","bond"};\
But i need to get this string from a text file that I would needed to have created. Please help me, I need this for my java assignment which it to build a hangman game (these are the words that are going to be guessed).
4 Answers 4
you can store these values in CSV (comma separated variables) in a file, like below.
atom,electron,oxyegn,explosion,combustion,flask,laser,molecule,ion,bond
While retrieving, you can read the contents of the file and split the line by comma like below
String s = ...read line form file...
String[] word = s.split(",");
Also, if you need to save some new values, you can do something like below (if you are using Java8)
String s = Stream.of(word).collect(Collectors.joining(","));
... save s in file...
1 Comment
Here's how I solved it:
package org.gooeybits.meltdown.utilities;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by Yohanan Ben Abrahams.
*/
public class Main {
private String[] words = null;
public Main() {}
public Main run() {
this.words = loadWordsFromFile("/your/path/to/file.txt");
return this;
}
private String[] loadWordsFromFile(String url) {
String currentLine;
List<String> words = new ArrayList<>();
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(url));
while ((currentLine = bufferedReader.readLine()) != null) {
String[] split = currentLine.split("\\W");
words.addAll(Arrays.asList(split));
}
} catch (IOException e) {
System.err.print("Could not open the word file: " + e.getMessage());
e.printStackTrace();
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return words.toArray(new String[words.size()]);
}
public String[] getWords() {
return words;
}
public static void main(String[] args) {
String[] words = new Main().run().getWords();
for (String word : words) {
System.out.println(word);
}
}
}
Comments
You can use a StreamTokenizer :
List<String> wordList = new ArrayList<String>();
Reader reader = new StringReader("atom electron ...");//replace this with a FileReader in you case
StreamTokenizer tokenizer = new StreamTokenizer(reader);
while(tokenizer.nextToken() != StreamTokenizer.TT_EOF){
wordList.add(tokenizer.sval);
}
reader.close();
And if you really need an array :
String[] words = wordList.toArray(new String[worldList.size()];
3 Comments
Reader reader = new StringReader("atom electron ...");
with Reader reader = new FileReader("/path/to/your/textfile");
java.io.StreamTokenizer
)If you do not wish to use any external imports, the following code would work:
public class TestStrings {
private String[] namesList;
public TestStrings() {
String filePath = "path/to/file";
this.namesList = readFile(filePath).split(",");
}
private static String readFile(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}