Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
bufferedwriter拒绝写入文本文件(Java)_Java_File_Writer - Fatal编程技术网

bufferedwriter拒绝写入文本文件(Java)

bufferedwriter拒绝写入文本文件(Java),java,file,writer,Java,File,Writer,每当我在代码中调用我的方法时,尽管正确地打开和关闭了BufferedWriter(我想),它仍然拒绝打印到它要打印的文本文件中 这是我的密码: public Student(String nameInput, String gradeInput) throws IOException { BufferedWriter o = new BufferedWriter(new FileWriter("Students.txt")); name = nameInp

每当我在代码中调用我的方法时,尽管正确地打开和关闭了BufferedWriter(我想),它仍然拒绝打印到它要打印的文本文件中 这是我的密码:

public Student(String nameInput, String gradeInput) throws IOException
    {
        BufferedWriter o = new BufferedWriter(new FileWriter("Students.txt"));
        name = nameInput;
        grade = gradeInput;
        o.write(gradeInput);
        o.newLine();
        o.write(nameInput);
        o.close(); 
    }

在关闭
BufferedWriter
之前尝试使用
o.flush()
,即
o.close()

首先需要在方法中添加返回类型,或者如果Student是返回类型,则需要在调用方法Student()的位置指定方法名称你能证明代码不需要在该方法中添加返回吗?你如何调用这个构造函数?(从签名来看,我认为这是一个
学生
类的构造器。)因为写
新学生(“名字”,“等级”)
在另一个空的
main
方法中,运行它会创建“Students.txt”文件,内容正确。@NamrataShukla我相信它是一个构造函数。Rishabh先生已经使answerResources应该在finally块中关闭!JIC!
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class Main {

    public static void Student(String nameInput, String gradeInput) throws IOException
    {
        BufferedWriter o = new BufferedWriter(new FileWriter("Students.txt"));
        String name = nameInput;
        String grade = gradeInput;
        o.write(gradeInput);
        o.newLine();
        o.write(nameInput);
        o.close(); 
    }
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        Student("ABC","A");
    }

}