简体   繁体   English

Java中的BufferReader

[英]BufferReader in Java

I have a problem with BufferReader and OutputStream in Java. 我在Java中遇到BufferReader和OutputStream的问题。 My aim: when you insert something from a keyboard - it goes to the file. 我的目标是:当您从键盘上插入某些内容时-它会转到文件中。 How should I correct my code? 我应该如何更正我的代码?

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);
        }
    }
}

Thanks! 谢谢!

I'd use Scanner and PrintWriter 我会使用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>

Code: 码:

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();
    }
}

HI I am providing a sample code through which you can write in the file after user enters characters or line from keyboard. 嗨,我提供了一个示例代码,您可以在用户从键盘输入字符或行后通过该代码编写文件。

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());
    }

In the our.write pass the line(variable) string argument and the string will be written in that file. our.write传递中, line(variable)字符串参数和字符串将被写入该文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM