java-读取文本文件并将文件中的字符串分配给变量

我的代码有一些问题.我希望能够从文本文件中读取输入,并从每一行或空格之间获取字符串,并将它们分配给要传递给对象的变量.

我的第一个问题是我的程序错误地读取了我的一行,并忽略了变量的第一个字母,第二个问题是我不知道如何使我的程序在同一行读取两个字符串并将它们分配给不同的变量.

    System.out.println("Input the file name of the text file you want to open:(remember .txt)");
    keyboard.nextLine();
    String filename=keyboard.nextLine();

    FileReader freader=new FileReader(filename);
    BufferedReader inputFile=new BufferedReader(freader);

    courseName=inputFile.readLine();

    while (inputFile.read()!= -1) {
        fName=inputFile.readLine(); 
        lName=inputFile.readLine();
        officeNumber=inputFile.readLine();
    }
    System.out.println(fName);
    Instructor inst=new Instructor(fName,lName,officeNumber);
    System.out.println(inst);
    inputFile.close();

}

我不太擅长使用FileReader,并尝试使用扫描仪键盘方法,但它导致我遇到更多错误:(

输出:
来自文件(F)或键盘(K)的输入:
F
输入您要打开的文本文件的文件名:(记住.txt)
test.txt
bun头
圆圆韩元的办公室号码为空

文本文件:
梅瑟教授
bun头
赢了

解决方法:

您必须使用readLine()读取一行,然后说要使用空格进行拆分.

所以你必须做这样的事情

    String line=null;
    List<Course> courses = new ArrayList<>();
        while ((line = inputFile.readLine())!= null) {
            String[] arrayLine= line.split("\\s+"); // here you are splitting with whitespace 
            courseName = arrayLine[0]
            lName=arrayLine[1];
            officeNumber=arrayLine[2];
            list.add(new Course(courseName,lName,officeNumber));   
          // you sure want do something with this create an object for example

        }

 // in some part br.close();

这里有一个例子How to read a File

上一篇:详解 字符便捷流


下一篇:在注册的时候如何让用户选定头像的时候有预览的功能