2012-09-19 3 views
0

이것은 내가 찾은 것입니다. 그러나이 코드에서 여러분이 넣은 것에 대한 행을 읽었습니다. 나는 그것을 원하지 않습니다.명령 프롬프트에서 출력을 가져 와서 언어를 사용하여 텍스트 파일을 만드는 방법 Java

저는 Knight 's Tour라는 프로그램을하고 있는데, 명령 프롬프트에서 결과를 얻습니다. 명령 프롬프트에서 줄을 읽고 knight.txt라는 출력 파일을 저장하기 만하면됩니다. 누구든지 나를 도울 수 있습니까? 감사.

try 
{ 
    //create a buffered reader that connects to the console, we use it so we can read lines 
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 

    //read a line from the console 
    String lineFromInput = in.readLine(); 

    //create an print writer for writing to a file 
    PrintWriter out = new PrintWriter(new FileWriter("output.txt")); 

    //output to the file a line 
    out.println(lineFromInput); 

    //close the file (VERY IMPORTANT!) 
    out.close(); 
} 

catch(IOException e) 
{ 
    System.out.println("Error during reading/writing"); 
} 
+0

당신이 원하는 것을하지 않는 코드를 게시하는 데 별 도움이되지 않습니까? – EJP

답변

5

Java 용으로 필요하지 않습니다. 그냥 파일로 게임의 출력을 리디렉션 :

game > knight.txt 
+0

그렇게하는 자바 코드를 작성하지 않아도됩니다. 필자가 작성한 프로그램은 Java 코드입니다. –

+1

아니요, Java가 필요하지 않습니다. 터미널이나 명령 프롬프트 (IDE와 반대)에서 Java 프로그램을 실행하고 출력을 텍스트 파일로 리디렉션하기 위해'>'를 사용하십시오 네가 원해. – Wires77

0

당신이 예에서 보일 수 있습니다, 그것은 파일이이 파일에 추가하는 방법을 보여 존재하는 경우, 파일에 데이터를 기록하는 방법을 보여줍니다

public class FileUtil { 

    public void writeLinesToFile(String filename, 
           String[] linesToWrite, 
           boolean appendToFile) { 

    PrintWriter pw = null; 

    try { 

     if (appendToFile) { 

     //If the file already exists, start writing at the end of it. 
     pw = new PrintWriter(new FileWriter(filename, true)); 

     } 
     else { 

     pw = new PrintWriter(new FileWriter(filename)); 
     //this is equal to: 
     //pw = new PrintWriter(new FileWriter(filename, false)); 

     } 

     for (int i = 0; i < linesToWrite.length; i++) { 

     pw.println(linesToWrite[i]); 

     } 
     pw.flush(); 

    } 
    catch (IOException e) { 
     e.printStackTrace(); 
    } 
    finally { 

     //Close the PrintWriter 
     if (pw != null) 
     pw.close(); 

    } 

    } 

    public static void main(String[] args) { 
    FileUtil util = new FileUtil(); 
    util.writeLinesToFile("myfile.txt", new String[] {"Line 1", 
                 "Line 2", 
                 "Line 3"}, true); 
    } 
} 
+0

그래서 'if'를 없애고 PrintWriter를 만들 때 두 번째 매개 변수로 'append'를 사용하십시오. 9 줄의 코드와 주석을 하나로 변환 하시겠습니까? – EJP

0

게시 한 코드에서 텍스트 파일에 출력 할 문자열을 lineFromInput으로 변경하십시오.

0

자바에서 파일 작업을 사용하여 파일에 출력을 쓰는 것이지만 다음과 같이 쉬운 방법으로 수행 할 수 있습니다. 이 코드는 필요하지 않습니다. 출력은

file > outputfile 

에 의해 리디렉션 될 수 있습니다. 이것은 자바와 독립적입니다.

관련 문제