我想将http://docs.oracle.com/javase/tutorial/collections/interfaces/examples/dictionary.txt复制到数组中以进行刽子手游戏。到目前为止,我有这个...
url = new URL("http://docs.oracle.com/javase/tutor… );
urlConn = url.openConnection();
urlConn.getInputStream());
inStream in = new InputStreamReader("dictionary.txt");
urlConn.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String nextLine;
String[] secretwordbank;
secretwordbank = new String[80368];
secretwordbank是一个表示单词字典的数组。这可能是一个数组太大,所以我愿意接受优化它的想法。谁知道怎么做?
答案 0 :(得分:1)
您是否真的只是不确定如何根据换行符将BufferedReader
转换为字符串数组(或其他集合)?如果是这样,我建议使用Guava:
List<String> lines = CharStreams.readLines(reader);
(顺便说一句,我建议在创建InputStreamReader
时指定编码 - 否则它将使用平台默认编码。理想情况下,您应该使用响应中的内容类型标头来确定编码。 ..有更高级别的HTTP库可以为您完成所有这些工作,例如HttpClient。)
答案 1 :(得分:1)
使用此Java代码构建单词列表:
URL url = new URL("http://docs.oracle.com/javase/tutorial/collections/interfaces/examples/dictionary.txt");
URLConnection urlConn = url.openConnection();
InputStream in = urlConn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String nextLine;
List<String> secretwordbank = new ArrayList<String>();
while ((nextLine = br.readLine()) != null) {
secretwordbank.add(nextLine);
}
System.out.println("Secret Word List: " + secretwordbank);
修改:如果您希望获得array of String
而不是List<String>
String[] wordBankArr = secretwordbank.toArray(new String[0]);
System.out.println("Secret Word Array: " + Arrays.toString(wordBankArr));