我有一个字符串数组:
String [] word = {“atom”,“electron”,“oxyegn”,“explosion”,“combustion”,“flask”,“laser”,“molecule”,“ion”,“bond”}; \
但我需要从我需要创建的文本文件中获取此字符串。请帮助我,我需要这个用于我的java任务,它建立一个刽子手游戏(这些是将被猜测的词)。
答案 0 :(得分:1)
您可以将这些值以CSV(逗号分隔的变量)存储在文件中,如下所示。
atom,electron,oxyegn,explosion,combustion,flask,laser,molecule,ion,bond
在检索时,您可以阅读文件的内容,并用逗号分隔行,如下所示
String s = ...read line form file...
String[] word = s.split(",");
此外,如果您需要保存一些新值,您可以执行以下操作(如果您使用的是Java8)
String s = Stream.of(word).collect(Collectors.joining(","));
... save s in file...
答案 1 :(得分:0)
您可以使用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();
如果你真的需要一个阵列:
String[] words = wordList.toArray(new String[worldList.size()];
答案 2 :(得分:0)
如果您不想使用任何外部导入,则以下代码可以使用:
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();
}
}
答案 3 :(得分:0)
以下是我如何解决它:
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);
}
}
}