ニック、あなたは私たちにパズルの最後のピースをくれました。読み取る行数がわかっている場合は、ファイルを読み取る前に、その長さの配列を定義するだけです。
何かのようなもの...
String[] wordArray = new String[10];
int index = 0;
String word = null; // word to be read from file...
// Use buffered reader to read each line...
wordArray[index] = word;
index++;
正直なところ、この例はあまり意味がないので、これら2つの例を実行しました
1つ目は、Alexが提案した概念を使用しており、ファイルから不明な行数を読み取ることができます。
唯一のトリップアップは、行が複数の1行フィードで区切られている場合です(つまり、単語間に余分な行があります)
public static void readUnknownWords() {
// Reference to the words file
File words = new File("Words.txt");
// Use a StringBuilder to buffer the content as it's read from the file
StringBuilder sb = new StringBuilder(128);
BufferedReader reader = null;
try {
// Create the reader. A File reader would be just as fine in this
// example, but hay ;)
reader = new BufferedReader(new FileReader(words));
// The read buffer to use to read data into
char[] buffer = new char[1024];
int bytesRead = -1;
// Read the file to we get to the end
while ((bytesRead = reader.read(buffer)) != -1) {
// Append the results to the string builder
sb.append(buffer, 0, bytesRead);
}
// Split the string builder into individal words by the line break
String[] wordArray = sb.toString().split("\n");
System.out.println("Read " + wordArray.length + " words");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception e) {
}
}
}
2つ目は、単語を既知の長さの配列に読み取る方法を示しています。これはおそらくあなたが実際に欲しいものに近いです
public static void readKnownWords()
// This is just the same as the previous example, except we
// know in advance the number of lines we will be reading
File words = new File("Words.txt");
BufferedReader reader = null;
try {
// Create the word array of a known quantity
// The quantity value could be defined as a constant
// ie public static final int WORD_COUNT = 10;
String[] wordArray = new String[10];
reader = new BufferedReader(new FileReader(words));
// Instead of reading to a char buffer, we are
// going to take the easy route and read each line
// straight into a String
String text = null;
// The current array index
int index = 0;
// Read the file till we reach the end
// ps- my file had lots more words, so I put a limit
// in the loop to prevent index out of bounds exceptions
while ((text = reader.readLine()) != null && index < 10) {
wordArray[index] = text;
index++;
}
System.out.println("Read " + wordArray.length + " words");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception e) {
}
}
}
これらのいずれかが役立つと思われる場合は、私が採用したのは彼の考えであるため、私に小さな賛成票を投じて、アレックスの答えが正しいかどうかを確認することをお勧めします。
これで、使用する改行について本当に心配している場合は、値を介してシステムで使用されている値を見つけることができますSystem.getProperties().getProperty("line.separator")
。