这是我的问题:
a method readLine that reads a line from the file specified in fileName and returns the line a String.
我要做的是使用 eclipse 读取一些信息并将其写入文本文件。这是我的代码:
public class FileController {
private String fileName;
public FileController(){
String fileName = "student.txt";
}
public FileController(String fileName){
this.fileName = fileName;
}
public String readLine(){
String line ="";
try{
FileReader fr = new FileReader(fileName);
Scanner sc = new Scanner(fr);
while(sc.hasNextLine()){
Student stud = new Student(sc.nextLine());
line = stud.toString();
}
fr.close();
}catch(FileNotFoundException exception){
System.out.println("File " + fileName + " was not found");
}catch(IOException exception){
System.out.println(exception);
}
return line;
}
public void writeLine(String input){
try{
FileWriter fw = new FileWriter(fileName,true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outFile = new PrintWriter(bw);
outFile.println(input);
outFile.close();
}catch(IOException exception){
System.out.println(exception);
}
}
public static void main (String [] args){
FileController fc = new FileController("student.txt");
String input = "1234567H;Gabriel;23/12/1994;56;67;87";
fc.readLine();
fc.writeLine(input);
}
通过将记录添加到文本文件中,这可以完美地工作。但是,那里的控制台没有显示结果。所以据我所知,错误在于 readLine()。当我使用 void 时,它工作得很好。但问题要求我返回一个字符串。有人知道如何解决这个问题吗?
- 当我在 while 循环中执行 println 时,其中存储了记录。我猜程序采用了 String file=""; 这一行并返回结果。那么如何在 while 循环中获取 line 的结果并替换为初始化呢?