Java中的BufferReader

时间:2011-04-23 08:59:53

标签: java outputstream

我在Java中遇到BufferReader和OutputStream的问题。我的目标:当你从键盘插入东西时 - 它会转到文件中。我该如何更正我的代码?

import java.io.*;

class IntoFile {
    public static void main(String[] args) throws Exception{
        try {
            BufferedReader sisse = new BufferedReader(new InputStreamReader(System.in));
            System.out.print ("Insert something: ");
            String s = sisse.readLine();

            byte[] buf = new byte[1024];
            OutputStream valja = new FileOutputStream(new File(args[0]));
            String line = null;
            while ((line = br.readLine()) != null) {

                }
            valja.close();
        } 
        catch (IOException e) {
            System.out.println ("I/O: " + e);
        }
    }
}

谢谢!

2 个答案:

答案 0 :(得分:1)

我使用Scanner和PrintWriter

C:\Documents and Settings\glowcoder\My Documents>javac Dmitri.java

C:\Documents and Settings\glowcoder\My Documents>java Dmitri
test
woohoo
quit

C:\Documents and Settings\glowcoder\My Documents>more out.txt
test
woohoo
quit

C:\Documents and Settings\glowcoder\My Documents>

代码:

import java.io.*;
import java.util.*;
class Dmitri {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(System.in);
        PrintWriter out = new PrintWriter("out.txt");
        while(in.hasNextLine()) {
            String line = in.nextLine();
            out.println(line);
            out.flush(); // not necessary every time, but simple to do so
            if(line.equalsIgnoreCase("QUIT")) break;
        }
        out.close();
    }
}

答案 1 :(得分:0)

我正在提供一个示例代码,您可以在用户从键盘输入字符或行后在文件中写入。

try{
    // Create file 
    FileWriter fstream = new FileWriter("out.txt");
        BufferedWriter out = new BufferedWriter(fstream);
    out.write("Hello Java");
    //Close the output stream
    out.close();
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }

my.write 中传递 line(variable)字符串参数,该字符串将写入该文件中。