2010-03-04 4 views
3

I가이 부분에 파일을 여는 클래스 :저장 파일 저장 대화 상자

JFileChooser jfc = new JFileChooser(); 
int result = jfc.showSaveDialog(this); 
if (result == JFileChooser.CANCEL_OPTION) 
    return; 
File file = jfc.getSelectedFile(); 
InputStream in; 
try { 
    in = new FileInputStream(f); 

    OutputStream st=new FileOutputStream(jfc.getSelectedFile()); 
    st.write(in.read()); 
    st.close(); 
} catch (FileNotFoundException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} catch (IOException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

:

JFileChooser chooser=new JFileChooser(); 
chooser.setCurrentDirectory(new File(".")); 
int r = chooser.showOpenDialog(ChatFrame.this); 
if (r != JFileChooser.APPROVE_OPTION) return; 
try { 
    Login.is.sendFile(chooser.getSelectedFile(), Login.username,label_1.getText()); 
} catch (RemoteException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

은 그때와 다른 파일에이 파일을 저장하려면 빈 파일 만 생성합니다! 이 문제를 해결하려면 어떻게해야합니까? (내 수업에서 모든 종류의 파일을 열어 저장하십시오.)

+1

조언 : 당신은 또한'FileInputStream에의 in'을 닫아야합니다. –

답변

1

파일의 끝까지 읽어야합니다. in 현재 하나의 읽기만 수행합니다. 단지 스트림에서 한 바이트를 읽고) (in.read을하지만 실제로 파일 복사 할 전체 스트림을 통해 스캔 알면 있습니다 : 여기

+0

도와 주셔서 대단히 감사합니다. – samuel

+0

@samuel 답변을 투표/수락함으로써 감사를 표시 할 수 있습니다. –

5

http://www.java-examples.com/read-file-using-fileinputstream가 문제의 예를 참조하십시오

OutputStream st=new FileOutputStream(jfc.getSelectedFile()); 
byte[] buffer=new byte[1024]; 
int bytesRead=0; 
while ((bytesRead=in.read(buffer))>0){ 
    st.write(buffer,bytesRead,0); 
} 
st.flush(); 
in.close(); 
st.close(); 

또는과를 apache-commons-io에서 도우미 :

OutputStream st=new FileOutputStream(jfc.getSelectedFile()); 
IOUtils.copy(in,st); 
in.close(); 
st.close(); 
+0

감사합니다. 내 친구가 내 문제를 해결해주었습니다. – samuel

관련 문제