2016-07-03 2 views
0

FileOutputStream 및 BufferedOutputStream을 사용하여 파일을 작성하는 Java 클래스가 있습니다. 이것은 잘 작동하지만 제 의도는 자바에 파일을 몇 개나 쓰고 싶다는 것입니다. 여기 내 코드는 다음 fileBack 방법은 루프를 n 번에 대한 내 다른 클래스에서 호출 Java에서 파일 목록 작성 방법

public class FileToBeTaken{ 


public void fileBack(byte [] output) { 

    FileOutputStream fop = null; 
    BufferedOutputStream bos = null; 
     File file; 


     try {  
      file= new File("/Users/user/Desktop/newfile.txt"); 

      fop = new FileOutputStream(file); 

      bos = new BufferedOutputStream(fop); 

      // if file doesnt exists, then create it 
      if (!file.exists()) { 
       file.createNewFile(); 
      } 



      bos.write(output); 
      bos.flush(); 
      bos.close(); 

      System.out.println("Done"); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       if (bos != null) { 
        bos.close(); 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

} 

자바

로 작성되었습니다. 그래서 매번 필자는 필자의 코드가 필자의 마지막 반복을 위해서 파일을 가져 가기 때문에 필자의 데스크탑에 새로운 파일을 작성해야한다. 또한이 클래스에 대한 매개 변수로 각 반복에 대해 "byte [] 출력으로 가져온 바이트 배열 하나를 보냅니다.

+0

당신이 runnale 예제를 제공 주실 래요? – Colourfit

+0

당신은 파일의 내용에 대해 매개 변수를 사용하기 때문에 함수에 매개 변수를 전달할 수 있다는 것을 이미 이해하고 있습니다. 파일 이름을 매개 변수로 전달하지 못하게하는 이유를 모르겠습니다. – njzk2

+0

@ njzk2 왜냐하면 내가 위에서 쓴이 클래스 안에서이 파일 이름을 만들고 싶기 때문에 어떻게 다른 클래스의 매개 변수로 전달할 수 있을지 모르겠다. –

답변

0

파일 경로 ..newfile.txt을 가져 와서 해당 함수의 매개 변수로 만드십시오. n 시간을 당신은 main에 루프를 넣을 수 있습니다 또는 누구든지이 개체를 인스턴스화하고 호출. 전혀 그 도움을합니까?

+0

부분을 이해하지 못하기 때문에 코드를 적어주세요. 당신은 "함수에 대한 매개 변수로" –

+0

@ alex10, 내가 생각하기 때문에 당신이'public void fileBack (byte [] output) {'에서 메소드 서명을이 public void fileBack (String fileName, byte [] output) {','newfile.txt'의 경로를'fileBack' 메소드에서 사용하도록 보냅니다. –

2

변경 public void fileBack(byte [] output) {

public void fileBack(String fileName, byte [] output) {

그런 다음 파일 이름을 제공하여 다른 클래스에서 fileBack 메서드를 호출하는 위치를 변경합니다. 즉

byte output[] = //You already provide this byte array 

String fileName = "/Users/user/Desktop/newfile.txt" 

fileBack(fileName, output); 
0

단지 FileToBeTaken 클래스 내에서 하나 개의 정적 및 개인 정수 필드를 추가합니다.

private static int index=0; 

그래서 질문 주석에서 언급 한 것처럼이 클래스에 파일 이름을 전달할 필요가 없습니다.

내가 다음

위에 쓴 fileBack 방법에서 사용이 클래스 내부에 이러한 파일 이름과 incremet을 한 번 그 방법의 각 시간을 만들려고하기 때문이다.

public class FileToBeTaken { 

    // index or number of new file, also number of all written files 
    // because it increments each time you call fileBack method. 
    private static int index = 0; 

    public void fileBack(byte[] output) { 

     FileOutputStream fop = null; 
     BufferedOutputStream bos = null; 
     File file; 

     try { 

      // use user_dir to place files on desktop, 
      // even on other machines which have other names except user. 
      String user_dir = System.getProperty("user.home").replace("\\", "/"); 

      // use index to create name of file. 
      file = new File(user_dir+"/Desktop/newfile_" + (index++) + ".txt"); 

      fop = new FileOutputStream(file); 
      bos = new BufferedOutputStream(fop); 

      // if file doesnt exists, then create it 
      if (!file.exists()) { 
       file.createNewFile(); 
      } 

      bos.write(output); 
      bos.flush(); 
      bos.close(); 

      System.out.println("Done - "+file.getName()); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       if (bos != null) { 
        bos.close(); 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
}  

방법을 사용하기 : 여기
는 코드의 변경입니다

for (int i = 0; i < 10; i++) { 
    new FileToBeTaken().fileBack("some text".getBytes()); 
} 

출력 :

Done - newfile_0.txt 
Done - newfile_1.txt 
Done - newfile_2.txt 
Done - newfile_3.txt 
Done - newfile_4.txt 
Done - newfile_5.txt 
Done - newfile_6.txt 
Done - newfile_7.txt 
Done - newfile_8.txt 
Done - newfile_9.txt 
+0

나는 당신에게 감사하는 방법을 모른다. 정말 도움이되었습니다.Thnx 많은 남자와 신이 당신을 축복합니다 –

+0

@ alex10 당신의 환영, 당신이 내 대답이 유용하다고 생각한다면, 그냥 투표하고 그것을 다른 사람들과 공유하십시오 :), 신의 축복이있어. –

+0

나는 그것이 나를 위해 일했던 순간부터 그것을 투표했다. –