2011-03-22 9 views
8

मेरे पास एक फ़ाइल example.tar.gz है और मुझे अलग-अलग नाम example_test.tar.gz के साथ किसी अन्य स्थान पर कॉपी करने की आवश्यकता है। मैंविभिन्न स्थान पर फ़ाइल कॉपी और नाम बदलें

private void copyFile(File srcFile, File destFile) throws IOException 
    { 
      InputStream oInStream = new FileInputStream(srcFile); 
      OutputStream oOutStream = new FileOutputStream(destFile); 

      // Transfer bytes from in to out 
      byte[] oBytes = new byte[1024]; 
      int nLength; 
      BufferedInputStream oBuffInputStream = 
          new BufferedInputStream(oInStream); 
      while ((nLength = oBuffInputStream.read(oBytes)) > 0) 
      { 
       oOutStream.write(oBytes, 0, nLength); 
      } 
      oInStream.close(); 
      oOutStream.close(); 
    } 
} 

जहां

String from_path=new File("example.tar.gz"); 
File source=new File(from_path); 

File destination=new File("/temp/example_test.tar.gz"); 
      if(!destination.exists()) 
       destination.createNewFile(); 

और फिर

copyFile(source, destination); 

साथ की कोशिश की लेकिन यह काम नहीं करता। पथ ठीक है। यह प्रिंट करता है कि फाइल मौजूद है। क्या कोई मदद कर सकता है?

+0

कोशिश 'फ्लश()' अपनी धाराओं से पहले 'पास()' यह ing transferTo को बदल दिया है। –

+0

इस पोस्ट को अपनी पोस्ट में सही करें: 'स्ट्रिंग से_पैथ = नई फ़ाइल ("example.tar.gz"); ' –

+2

@ मोहम्मद, फ्लश को – bestsss

उत्तर

6
I would suggest Apache commons FileUtils or NIO (direct OS calls) 

या जोश को बस इस

क्रेडिट्स - standard-concise-way-to-copy-a-file-in-java


File source=new File("example.tar.gz"); 
File destination=new File("/temp/example_test.tar.gz"); 

copyFile(source,destination); 

अपडेट:

से @bestss

public static void copyFile(File sourceFile, File destFile) throws IOException { 
    if(!destFile.exists()) { 
     destFile.createNewFile(); 
    } 

    FileChannel source = null; 
    FileChannel destination = null; 
    try { 
     source = new RandomAccessFile(sourceFile,"rw").getChannel(); 
     destination = new RandomAccessFile(destFile,"rw").getChannel(); 

     long position = 0; 
     long count = source.size(); 

     source.transferTo(position, count, destination); 
    } 
    finally { 
     if(source != null) { 
     source.close(); 
     } 
     if(destination != null) { 
     destination.close(); 
     } 
    } 
} 
+0

का सबसे अच्छा तरीका है FileStreams का उपयोग करना फ़ाइलों की प्रतिलिपि करने में अक्षम हो सकता है,' java.nio.channels.FileChannel.transferTo' देखें – bestsss

संबंधित मुद्दे