Java 在字符串数组中加载.text文件

Java 在字符串数组中加载.text文件,java,arrays,string,file-io,Java,Arrays,String,File Io,如何将.txt文件加载到字符串数组中 private void FileLoader() { try { File file = new File("/some.txt"); Scanner sc = new Scanner(new FileInputStream(file), "Windows-1251"); //Obviously, exception int i = 0; while (

如何将.txt文件加载到字符串数组中

private void FileLoader() {
    try {
        File file = new File("/some.txt");
        Scanner sc = new Scanner(new FileInputStream(file), "Windows-1251");
            //Obviously, exception
            int i = 0;
        while (sc.hasNextLine()) {
        morphBuffer[i] = sc.nextLine();
        i++;
            //Obviously, exception  
        }
        sc.close();
    } catch (FileNotFoundException e) {
        JOptionPane.showMessageDialog(null, "File not found: " + e);
        return;
    }
}
数组的长度有问题,因为我不知道数组的长度。 我当然看到了,但是没有字符串的数组。我需要它,因为我必须处理整个文本,也必须处理空字符串。
如何将文本文件加载到字符串数组中?

您可以使用
Collection
ArrayList

while (sc.hasNextLine()) {
    list.add(sc.nextLine());
    i++;
        //Obviously, exception  
}
使用列表

private void FileLoader() {
try {
    File file = new File("/some.txt");
    Scanner sc = new Scanner(new FileInputStream(file), "Windows-1251");
    List<String> mylist = new ArrayList<String>();
    while (sc.hasNextLine()) {
        mylist.add(sc.nextLine());
    }
    sc.close();
} catch (FileNotFoundException e) {
    JOptionPane.showMessageDialog(null, "File not found: " + e);
    return;
}
}
private void FileLoader(){
试一试{
File File=新文件(“/some.txt”);
Scanner sc=新扫描仪(新文件输入流(文件),“Windows-1251”);
List mylist=new ArrayList();
while(sc.hasNextLine()){
mylist.add(sc.nextLine());
}
sc.close();
}catch(filenotfounde异常){
showMessageDialog(null,“未找到文件:”+e);
返回;
}
}
从Java 7开始:


.谢谢大家的帮助!对不起,怎么办?我的意思是,如何在ArrayList中加载文本文件?我可以使用regex处理
ArrayList
吗?@linuxedhose您可以(几乎)以与数组相同的方式处理列表。如果愿意,您也可以将列表转换为数组。@linuxedhorse,您在当前代码中使用regex的具体位置是什么?我在类中的方法中使用regex,其中
FileLoader()
是,我正在使用最后一个。我可能会出错,但我认为
Charset.forName(“Windiws-1251”)
,而不是
Charset.forName(“Cp1251”)
。或者两者都是对的?@linuxedhorse
List<String> allLines = Files.readAllLines("/some.txt", Charset.forName("Cp1251"));
String[] allLines = Files.readAllLines("/some.txt", Charset.forName("Cp1251")).toArray(new String[0]);