如何读取 txt 文件,以便将所有单词都放在一个新的数组元素中,而不是每个新行都放在一个元素中?



我目前编写了一个能够读取.txt文件的代码,对于每个新行,它将被放置在数组元素中(不是很难(。它可以工作,但这不是我的初衷,我想将每个单词都放在一个新的数组元素中,而不是在每个新行之后。这是我当前的代码,有人可以帮忙吗?谢谢!

public static ArrayList<String> read_file() {
try {
ArrayList<String> data_base = new ArrayList<String>();
Scanner s1 = new Scanner(new File("C:\Users\Jcool\OneDrive\A Levels\Computer Science\CSV files\data convert\convert.txt"));
while(s1.hasNextLine()) {
data_base.add(s1.nextLine());
}
return data_base;
}catch(FileNotFoundException e) {
}
return null;
}

一次读取所有行并将它们拆分为数组。

private static String readAllBytes(String filePath) 
{
String content = "";
try
{
content = new String ( Files.readAllBytes( Paths.get(filePath) ) );
} 
catch (IOException e) 
{
e.printStackTrace();
}
return content;
}

创建一个名为readAllBytes的方法并像这样调用它;

/* String to split. */
String stringToSplit = readAllBytes(filePath);
String[] tempArray;
/* delimiter */
String delimiter = " ";//space if its a file contains words
/* given string will be split by the argument delimiter provided. */
tempArray = stringToSplit.split(delimiter);

如果您打算将行拆分为数组,请查看答案。

看看 split(String( 方法。它返回一个String[]。举个例子

String string = "AAA-BBB";
String[] parts = string.split("-");
String part1 = parts[0]; // AAA
String part2 = parts[1]; // BBB

最新更新