这应该列出用户定义的文本文件中的每个单词,然后将它们放入一个数组中。这是我长期以来第一次尝试java,我只知道这是一团糟。
public static String[] parse(String path) throws IOException {
List<String> list = new ArrayList<String>();
String line;
try <BufferedReader br = new BufferedReader(new FileReader(path))) {
while((line = br.readLine()) != null) {
// Trying to make sure I make words between the spaces and punctuation
for (int i = 0; i < line.length(); i++) {
int x;
if (Character.isLetter(line.charAt(i))) {
x = i;}
for (int a = x; a < line.length(); a++) {
if (!Character.isLetter(line.charAt(a))) {
String s = line.substring(x, a)
list.add(s);
i = a;
a = line.length() + 1;
}
}
}
}
}
String[] arr = list.toArray(new String[list.size()]);
return arr;
}
catch (Exception e) {
System.out.println("could not find file");
return null;
}
}
答案 0 :(得分:1)
如果要求从文件中获取所有单词并将其放入列表中,您可以通过以下更简单的方式完成此操作:
List<MyModel> data = (List<MyModel>)TempData.Peek("data");
你的清单现在可以包含所有单词。 将列表转换为字符串[] ..
while ((line = br.readLine()) != null) {
String[] words = line.split(" ");
// Now you have a String array containing each word in the current line
//Add all words to list as below.
list.addAll(Arrays.asList(words));
}
答案 1 :(得分:1)
我更喜欢拆分一个或多个空格字符(修剪线后),然后使用正则表达式删除所有字母而不是字母(而不是字符测试)。你可以在List.toArray
中使用一个空数组,它会为你调整大小。永远不要默默地吞下异常。像,
public static String[] parse(String path) throws IOException {
List<String> list = new ArrayList<>();
String line;
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
while ((line = br.readLine()) != null) {
String[] tokens = line.trim().split("\\s+");
for (String token : tokens) {
token = token.replaceAll("[^a-zA-Z]", "");
if (!token.isEmpty()) {
list.add(token);
}
}
}
return list.toArray(new String[0]);
} catch (Exception e) {
System.out.println("could not find file " + e.getMessage());
e.printStackTrace();
return null;
}
}
答案 2 :(得分:1)
在这种情况下,使用Scanner更合适,速度更快:
List<String> words = new ArrayList<>();
try (Scanner sc = new Scanner(new File(path))) {
//Everything that's not a character is treated as delimiter
sc.useDelimiter("[^a-zA-Z]+");
while (sc.hasNext()) {
words.add(sc.next());
}
}
对于Java 9来说,它甚至更简单:
final List<String> words;
try (Scanner sc = new Scanner(new File(path))) {
sc.useDelimiter("[^a-zA-Z]+");
words = sc.tokens().collect(Collectors.toList());
}