2011-04-23 4 views
0

Java의 BufferReader 및 OutputStream에 문제가 있습니다. 내 목표 : 키보드에서 무언가를 삽입하면 파일로 이동합니다. 내 코드를 어떻게 수정해야합니까?Java의 BufferReader

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

감사합니다.

+0

http://download.oracle.com/javase/1.4.2/docs/api /java/io/OutputStream.html. write (Byte []) – starcorn

답변

1

내가 스캐너 및 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> 

코드 : 당신이 API를 읽을 수

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

+1. 대학에있는 동안, 우리는 본질적으로 스캐너의 열악한 버전이었던 적절한 패키지를 사용하게되었습니다. 확실히이 대답을위한 좋은 수업입니다. – obfuscation

+0

@bfuscation은 불행합니다. 그들의 도서관에서 과시하려고하는 교수 또는 TA와 같을 것입니다. 그들이 실사를한다면, 학생들에게 자바 코어 라이브러리가 얼마나 강력한 지와 효과적으로 사용하는 방법을 학생들에게 보여줄 것입니다. 언어의 핵심 라이브러리를 아는 것은 (내 의견으로는) "그래, 그 언어를 안다."라고 말할 수있는 첫 단계입니다. – corsiKa

+0

네, 전적으로 동의합니다. 나중에 프로젝트에서 나는 표준 라이브러리를 사용하여 자신에게 익숙해 지도록 항상 의식적으로 선택했다. 결국, 독점적 인 코드에 의존하고 싶지도 않으며 원하지 않을 수도 있습니다. – obfuscation

0

안녕하세요 사용자가 키보드에서 문자 나 줄을 입력 한 후 파일에 쓸 수있는 샘플 코드를 제공하고 있습니다. our.write에서

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

라인 (가변) 스트링 인수를 전달하고, 해당 문자열이 파일에 기록한다.

+0

라는 메소드가 있습니다. 그것은 내가 필요한 것입니다 –

+0

안녕하세요 당신이 투표를 할 수 있습니다 또는 그것을 수락하십시오. 스캐너의 경우 – Ankit