簡體   English   中英

Java中的BufferReader

[英]BufferReader in Java

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

謝謝!

我會使用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();
    }
}

嗨,我提供了一個示例代碼,您可以在用戶從鍵盤輸入字符或行后通過該代碼編寫文件。

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

our.write傳遞中, line(variable)字符串參數和字符串將被寫入該文件中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM