0

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).

asked Jun 5, 2016 at 8:52

4 Answers 4

1

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...
answered Jun 5, 2016 at 8:58

1 Comment

Hi, thnx for the help, do you need code for creating the file, I am pretty new to incorporating text files into java, so the more specific the better :)
0

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);
 }
 }
}
answered Jun 5, 2016 at 10:19

Comments

0

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()];
answered Jun 5, 2016 at 9:17

3 Comments

thank you for your help. Since i am just learning file readers could you specify an example of how I may do this step by step?
replace the Reader reader = new StringReader("atom electron ..."); with Reader reader = new FileReader("/path/to/your/textfile");
Note that StreamTokenizer is a part of the java standard API (java.io.StreamTokenizer)
0

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();
 }
 }
answered Jun 5, 2016 at 9:32

3 Comments

Thank you, how do i use the string array, nameslist, outside of the main ?
Set the array to an instance variable within a constructor.
I am not sure how to do that, still learning the basics, could you show me an example please :)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.