简体   繁体   中英

BufferReader in Java

I have a problem with BufferReader and OutputStream in Java. 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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