这是我的问题:
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时它完美无缺。但问题要求我返回一个字符串。有谁知道如何解决这个问题?
答案 0 :(得分:1)
你正在覆盖while循环中的行:
try{
FileReader fr = new FileReader(fileName);
Scanner sc = new Scanner(fr);
while(sc.hasNextLine()){
Student stud = new Student(sc.nextLine());
line = stud.toString();
}
所以这意味着只有最后一行会传递给学生[最有可能是空白行]并且它可能不会打印任何内容,甚至可能会出现异常。使用StringBuffer并附加字符串然后返回。
编辑:
试试这个。
public String readLine(){
StringBuffer line =new StringBuffer();
try{
FileReader fr = new FileReader(fileName);
Scanner sc = new Scanner(fr);
while(sc.hasNextLine()){
Student stud = new Student(sc.nextLine());
line.append(stud.toString());
}
fr.close();
}catch(FileNotFoundException exception){
System.out.println("File " + fileName + " was not found");
}catch(IOException exception){
System.out.println(exception);
}
return line.toString();
}
编辑: 如果上面的代码也返回空白,那么最有可能的问题是Strudent“toString()”方法。它可能会返回空白。
编辑:
public String readLine(){
StringBuffer line =new StringBuffer();
try{
FileReader fr = new FileReader(fileName);
Scanner sc = new Scanner(fr);
while(sc.hasNextLine()){
Student stud = new Student(sc.nextLine());
line.append(stud.toString());
line.append("\n");
}
fr.close();
}catch(FileNotFoundException exception){
System.out.println("File " + fileName + " was not found");
}catch(IOException exception){
System.out.println(exception);
}
return line.toString();
}