2011-12-13 2 views
0

"Frankenstein-ed"Java의 첫 번째 부분은 완벽하게 작동하지만 두 번째 부분은 혼란스러운 말도 안되는 내용을 출력합니다. 결과의 변수는 사용자로부터의 입력입니다. 나는 당신이 Database/Analysis 배경에서 왔을 때 당신이 몇 초안에 뭔가를하고 오류가 발생하지 않는다는 것을 알기가 어려울 때, 나는 어리석은 이유 때문에 파싱을하기 전에 문자열을 먼저 UpperCase해야만했다. 나는 신용이 만기가되는 곳에 신용을 주었다. 코드 ...구문 분석 문자열 파일로 출력

MYFILE.TXT ---> [Ljava.lang.String 내에서, 19821f

import java.io.*; 
/*http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29*/ 

    public class StringParser { 

    public static void main (String arg[]) 
    throws FileNotFoundException { 
String result = "eggs toast bacon bacon butter ice beer".toUpperCase(); 
    String[] resultU = result.split("\\s"); 
    String[] y = resultU; 

    { 
for (int x=0; x< resultU.length; x++) 



    System.out.println(resultU[x]); 


    /*http://www.javacoffeebreak.com/java103/java103.html#output*/ 

      FileOutputStream out; // declare a file output object 
      PrintStream p; // declare a print stream object 

      try 
      { 
        // Create a new file output stream 
        // connected to "myfile.txt" 
        out = new FileOutputStream("myfile.txt"); 

        // Connect print stream to the output stream 
        p = new PrintStream(out); 

        p.println (resultU); 

        p.close(); 
      } 
      catch (Exception e) 
      { 
        System.err.println ("Error writing to file"); 
      } 
    } 
} 
} 

답변

2

배열의 각 요소에 대해 동일한 파일을 덮어 쓰는 것을 알고 있습니까? 단지를 만들려면 당신은 아마 당신의 코드를 업데이트해야하지만 당신은

out = new FileOutputStream("myfile.txt", true); // appends to existing file 

를 사용뿐만 아니라 실제 요소의 전체 배열

p.println(resultU[x]); // resultU without index prints the whole array - yuk! 

아닌 String 표현을 인쇄한다

출력 파일 및 배열의 ​​각 요소를 동일한 출력 스트림에 쓰십시오. 현재 방법은 약간 비효율적입니다.

뭔가

public static void main(String[] args) { 

    String result = "eggs toast bacon bacon butter ice beer".toUpperCase(); 

    PrintStream p = null; 

    try { 
     p = new PrintStream(new FileOutputStream("myfile.txt")); 

     for (String s : result.split("\\s")) { 
      p.println(s); 
      p.flush(); // probably not necessary 
     } 

    } catch (Exception e) { 
     e.printStackTrace(); // should really use a logger instead! 
    } finally { 
     try { 
      p.close(); // wouldn't need this in Java 7! 
     } catch (Exception e) { 
     } 
    } 
} 
+0

저는 자바에 익숙하지 않아서 불을 피우면서 배우려고합니다 ... :) 고마워요. 그것을 시험해 보도록하겠습니다 ... – Darren

+0

cool thanks H.D.! – Darren

+0

@Darren 그러면 정답으로 선택해야합니다.) –

0

@ 당신은 배열을 반복하고 각 요소를 한 후 하나를 작성해야합니다.

FileOutputStream out; // declare a file output object 
    PrintStream p; // declare a print stream object 
    try 
    { 
    out = new FileOutputStream("myfile.txt"); 
    p = new PrintStream(out); 
    for(String str:resultU) 
    { 
     p.println (str); 
    } 
    p.close(); 
    } 
    catch (Exception e) 
    { 
    System.err.println ("Error writing to file"); 
    } 
+0

저는 Java에 익숙하지 않으므로 이것을 수행하는 방법을 살펴 보겠습니다. – Darren

+0

스트림이'try' 블록 내에서 닫히기 때문에, 그 내부에 선언을 두는 것이 좋습니다. 하지만 코드는 거의 정확하게 내 것입니다. 거의 차이가 없습니다 :) – Jon

0

귀하의 라인처럼

p.println (resultU); 

은 배열 자체, 거기에없는 요소의 문자열 표현을 인쇄한다. 요소를 인쇄하려면 배열을 반복하여 개별적으로 인쇄해야합니다. 물론 The Arrays class에는이를 위해 편리한 방법이 있습니다.

0

"뒤죽박죽이 된 비 감각"은 메모리에있는 String 위치이지만 그다지 중요하지 않습니다.

문제에 대한 해결책은 이것이다 :

try { 
    FileOutputStream out = new FileOutputStream("myfile.txt", true); 
    PrintStream = new PrintStream(out); 

    for(String s : resultU) 
    p.println(s); 

    p.close(); 
} catch(Exception e) { 
    e.printStackTrace(); 
} 

이 전체 for 루프를 대체합니다.

+0

고마워요! "뒤죽박죽 인 말도 안되는 소리"는 컴퓨터와 관련된 것이라고 생각했습니다. 감사! – Darren