netbeans EOF在数据文件中不起作用,无法保存值

vawmfj5a  于 2022-11-10  发布在  其他
关注(0)|答案(1)|浏览(152)
public static void main(String[] args) throws IOException {
    InputStream istream;        
    int c;
    final int EOF = -1;
    istream = System.in; 
    FileWriter outFile =  new FileWriter("C:/Users/boamb/Documents/NetBeansProjects/DSA_BSE20BFT/src/week7/Data.txt",true);
    BufferedWriter bWriter = new BufferedWriter(outFile);
    System.out.println("Enter fruits to store in data File – Press Ctrl+Z to end ");    
    while ((c = istream.read()) != EOF)
    bWriter.write(c);
    bWriter.close();
    }

大家好,我尝试通过NETBEANS IDE中的系统输出在文件中插入数据,但问题是当我按CTRL+Z时,它不工作,程序仍在运行,当我手动停止它时,文件中没有保存任何数据。这是我的代码。

ki0zmccv

ki0zmccv1#

实际上我不明白当你的逻辑说“输入水果”时,依赖EOF的原因是什么。我的意思是你应该读一个字符串,而不是一个字节一个字节的,在这种情况下,终止符也将是一些字符串值,例如“end”:

public static void main( String[] args ) throws IOException{
    BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );
    FileWriter outFile = new FileWriter( "C:/Users/boamb/Documents/NetBeansProjects/DSA_BSE20BFT/src/week7/Data.txt", true );
    try ( BufferedWriter bWriter = new BufferedWriter( outFile ); ){
        String line;
        while( true ){
            System.out.println( "Enter fruits to store in data File – Enter 'end' to end " );
            line = br.readLine();
            if( "end".equals( line ) ){
                break;
            }
            bWriter.write( line );
            bWriter.newLine();
        }
        bWriter.flush();
    }
}

相关问题