2014-12-26 3 views
0

배열의 정수를 다른 줄로 구분 된 텍스트 파일로 출력하는 방법을 알고 싶습니다. 아래의 관련 코드는 있지만 프로그램을 실행할 때마다 파일이 만들어 지지만 파일 자체에 데이터가 저장되지 않습니다.배열의 내용을 Java의 텍스트 파일로 출력하는 방법은 무엇입니까?

public static void printToFile(double[] gravity)throws IOException 
{ 
    PrintWriter outputFile = new PrintWriter (new FileWriter("gravitydata.txt", true)); 
    for(int a = 0; a < 9; a++) 
    { 
     outputFile.println(gravity[a]); 
    } 
} 
+6

당신은'outputFile.close();를 호출하는 것을 잊어 버린다. –

+2

맞다 - 나에게 이길 수있어! –

답변

1
{ 
    PrintWriter outputFile = new PrintWriter (new FileWriter("gravitydata.txt", true)); 
    for(int a = 0; a < 9; a++) 
    { 
     outputFile.println(gravity[a]); 
    } 
    outputFile.close(); 

} 
2

당신은 close()에 파일 (파일을 닫습니다되는 FileWriter 닫힙니다 PrintWriter 닫기)를 가지고있다. 당신은 당신이 9를 하드 코딩하는 대신 배열 length 속성을 사용해야합니다 어느 경우에

public static void printToFile(double[] gravity) throws IOException 
{ 
    PrintWriter outputFile = new PrintWriter(
      new FileWriter("gravitydata.txt", true)) 
    try { 
     for(int a = 0; a < gravity.length; a++){ 
      outputFile.println(gravity[a]); 
     } 
    } finally { 
     outputFile.close(); 
    } 
} 

처럼

public static void printToFile(double[] gravity) throws IOException 
{ 
    try (PrintWriter outputFile = new PrintWriter(
      new FileWriter("gravitydata.txt", true))) { 
     for(int a = 0; a < gravity.length; a++){ 
      outputFile.println(gravity[a]); 
     } 
    } 
} 

또는 이전 finally 블록과 뭔가를 할 수있는 try-with-resources를 사용할 수 있습니다.

0

다음 방법은 Java 8의 내장 함수를 사용하여 (자체 파일 처리 및 루핑 작성을 피하기 위해) 좋은 방법이 될 수 있습니다.

public static void printToFile(double[] gravity) throws IOException { 
    // First, convert the double[] to a list of Strings 
    final List<String> doublesAsStrings = Arrays.stream(gravity) 
      .boxed() // Box it to Doubles 
      .map(g -> String.valueOf(g)) // Convert each Double to a String 
      .collect(Collectors.toList()); // Create a List<String> 

    // Then, write the list to the file 
    Files.write(new File("gravitydata.txt").toPath(), doublesAsStrings); 
} 

이전 응답에 비해 몇 가지 차이점이 있습니다

Files 클래스는 별도의 외부 루프가없는 등
  • 잡을/시도 처리하기 때문에 편리하게 데이터를 기록하는 데 사용됩니다
    • 스트리밍 API 이후에 필요합니다. ■ 인쇄 할 문자열 시퀀스를 만드는 데 사용됩니다.
    • 짧고 간결합니다.)
  • 관련 문제