⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 fileutil.java

📁 一个基于JAVA的多torrent下载程序
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
    }
    
    /**
     * Copy the given source file to the given destination file.
     * Returns file copy success or not.
     * @param _source source file
     * @param _dest destination file
     * @return true if file copy successful, false if copy failed
     */
    /*
    // FileChannel.transferTo() seems to fail under certain linux configurations.
    public static boolean copyFile( final File _source, final File _dest ) {
      FileChannel source = null;
      FileChannel dest = null;
      try {
        if( _source.length() < 1L ) {
          throw new IOException( _source.getAbsolutePath() + " does not exist or is 0-sized" );
        }
        source = new FileInputStream( _source ).getChannel();
        dest = new FileOutputStream( _dest ).getChannel();
      
        source.transferTo(0, source.size(), dest);
        return true;
      }
      catch (Exception e) {
        Debug.out( e );
        return false;
      }
      finally {
        try {
          if (source != null) source.close();
          if (dest != null) dest.close();
        }
        catch (Exception ignore) {}
      }
    }
    */
    
    public static boolean copyFile( final File _source, final File _dest ) {
      try {
        copyFile( new FileInputStream( _source ), new FileOutputStream( _dest ) );
        return true;
      }
      catch( Throwable e ) {
      	Debug.printStackTrace( e );
        return false;
      }
    }
    
    public static boolean copyFile( final File _source, final OutputStream _dest, boolean closeOutputStream ) {
        try {
          copyFile( new FileInputStream( _source ), _dest, closeOutputStream );
          return true;
        }
        catch( Throwable e ) {
        	Debug.printStackTrace( e );
          return false;
        }
      }
    public static void 
    copyFile( 
      InputStream   is,
      OutputStream  os ) 
    throws IOException {
      copyFile(is,os,true);
    }
    
    public static void 
	copyFile( 
		InputStream		is,
		OutputStream	os,
    boolean closeInputStream)
	
		throws IOException
	{
    	try{
    		
    		if ( !(is instanceof BufferedInputStream )){
    			
    			is = new BufferedInputStream(is);
    		}
    		
    		byte[]	buffer = new byte[65536*2];
			
    		while(true){
    			
    			int	len = is.read(buffer);
    			
    			if ( len == -1 ){
    				
    				break;
    			}
    			
    			os.write( buffer, 0, len );
    		}
    	}finally{
    		try{
        if(closeInputStream)
    			  is.close();
    		}catch( IOException e ){
    			
    		}
    		
    		os.close();
    	}
	}
    
    
    /**
     * Returns the file handle for the given filename or it's
     * equivalent .bak backup file if the original doesn't exist
     * or is 0-sized.  If neither the original nor the backup are
     * available, a null handle is returned.
     * @param _filename root name of file
     * @return file if successful, null if failed
     */
    public static File getFileOrBackup( final String _filename ) {
      try {
        File file = new File( _filename );
        //make sure the file exists and isn't zero-length
        if ( file.length() <= 1L ) {
          //if so, try using the backup file
          File bakfile = new File( _filename + ".bak" );
          if ( bakfile.length() <= 1L ) {
            return null;
          }
          else return bakfile;
        }
        else return file;
      }
      catch (Exception e) {
        Debug.out( e );
        return null;
      }
    }

    
    public static File
	getJarFileFromURL(
		String		url_str )
    {
    	if (url_str.startsWith("jar:file:")) {
        	
        	// java web start returns a url like "jar:file:c:/sdsd" which then fails as the file
        	// part doesn't start with a "/". Add it in!
    		// here's an example 
    		// jar:file:C:/Documents%20and%20Settings/stuff/.javaws/cache/http/Dparg.homeip.net/P9090/DMazureus-jnlp/DMlib/XMAzureus2.jar1070487037531!/org/gudy/azureus2/internat/MessagesBundle.properties
    			
        	// also on Mac we don't get the spaces escaped
        	
    		url_str = url_str.replaceAll(" ", "%20" );
        	
        	if ( !url_str.startsWith("jar:file:/")){
        		
       
        		url_str = "jar:file:/".concat(url_str.substring(9));
        	}
        	
        	try{
        			// 	you can see that the '!' must be present and that we can safely use the last occurrence of it
          	
        		int posPling = url_str.lastIndexOf('!');
            
        		String jarName = url_str.substring(4, posPling);
        		
        			//        System.out.println("jarName: " + jarName);
        		
        		URI uri = URI.create(jarName);
        		
        		File jar = new File(uri);
        		
        		return( jar );
        		
        	}catch( Throwable e ){
        	
        		Debug.printStackTrace( e );
        	}
    	}
    	
    	return( null );
    }

    public static boolean
	renameFile(
		File		from_file,
		File		to_file )
    {
    	if ( to_file.exists()){
    		Logger.log(new LogAlert(LogAlert.REPEATABLE, LogAlert.AT_ERROR,
					"renameFile: target file '" + to_file + "' already exists, failing"));
    		
    		return( false );
    	}
    	
    	if ( !from_file.exists()){
    		Logger
					.log(new LogAlert(LogAlert.REPEATABLE, LogAlert.AT_ERROR,
							"renameFile: source file '" + from_file
									+ "' already exists, failing"));
    		
    		return( false );
    	}
    	
    	if ( from_file.isDirectory()){
    		
    		to_file.mkdirs();
    		
    		File[]	files = from_file.listFiles();
    		
    		if ( files == null ){
    			
    				// empty dir
    			
    			return( true );
    		}
    		
    		int	last_ok = 0;
    		
    		for (int i=0;i<files.length;i++){
    			
  				File	ff = files[i];
				File	tf = new File( to_file, ff.getName());

    			try{
     				if ( renameFile( ff, tf )){
    					
    					last_ok++;
    					
    				}else{
    					
    					break;
    				}
    			}catch( Throwable e ){
    				
    				Logger.log(new LogAlert(LogAlert.REPEATABLE,
							"renameFile: failed to rename file '" + ff.toString() + "' to '"
									+ tf.toString() + "'", e));

    				break;
    			}
    		}
    		
    		if ( last_ok == files.length ){
    			
    			File[]	remaining = from_file.listFiles();
    			
    			if ( remaining != null && remaining.length > 0 ){
    				Logger.log(new LogAlert(LogAlert.REPEATABLE, LogAlert.AT_ERROR,
							"renameFile: files remain in '" + from_file.toString()
									+ "', not deleting"));
   				 
    			}else{
    				
    				if ( !from_file.delete()){
    					Logger.log(new LogAlert(LogAlert.REPEATABLE, LogAlert.AT_ERROR,
								"renameFile: failed to delete '" + from_file.toString() + "'"));
    				}
    			}
    			
    			return( true );
    		}
    		
    			// recover by moving files back
    		
      		for (int i=0;i<last_ok;i++){
        		
				File	ff = files[i];
				File	tf = new File( to_file, ff.getName());

    			try{
    				
    				if ( !renameFile( tf, ff )){
    					Logger.log(new LogAlert(LogAlert.REPEATABLE, LogAlert.AT_ERROR,
								"renameFile: recovery - failed to move file '" + tf.toString()
										+ "' to '" + ff.toString() + "'"));
    				}
    			}catch( Throwable e ){
    				Logger.log(new LogAlert(LogAlert.REPEATABLE,
							"renameFile: recovery - failed to move file '" + tf.toString()
									+ "' to '" + ff.toString() + "'", e));
   	   			    				
    			}
      		}
      		
      		return( false );
      		
    	}else{
			if ( 	(!COConfigurationManager.getBooleanParameter("Copy And Delete Data Rather Than Move")) &&
					from_file.renameTo( to_file )){
		  					
				return( true );
	
			}else{
				
				boolean		success	= false;
				
					// can't rename across file systems under Linux - try copy+delete
	
				FileInputStream		fis = null;
				
				FileOutputStream	fos = null;
				
				try{
					fis = new FileInputStream( from_file );
					
					fos = new FileOutputStream( to_file );
				
					byte[]	buffer = new byte[65536];
					
					while( true ){
						
						int	len = fis.read( buffer );
						
						if ( len <= 0 ){
							
							break;
						}
						
						fos.write( buffer, 0, len );
					}
					
					fos.close();
					
					fos	= null;
					
					fis.close();
					
					fis = null;
					
					if ( !from_file.delete()){
						Logger.log(new LogAlert(LogAlert.REPEATABLE,
								LogAlert.AT_ERROR, "renameFile: failed to delete '"
										+ from_file.toString() + "'"));
						
						throw( new Exception( "Failed to delete '" + from_file.toString() + "'"));
					}
					
					success	= true;
					
					return( true );
					
				}catch( Throwable e ){		
	
					Logger.log(new LogAlert(LogAlert.REPEATABLE,
							"renameFile: failed to rename '" + from_file.toString()
									+ "' to '" + to_file.toString() + "'", e));
					
					return( false );
					
				}finally{
					
					if ( fis != null ){
						
						try{
							fis.close();
							
						}catch( Throwable e ){
						}
					}
					
					if ( fos != null ){
						
						try{
							fos.close();
							
						}catch( Throwable e ){
						}
					}
					
						// if we've failed then tidy up any partial copy that has been performed
					
					if ( !success ){
						
						if ( to_file.exists()){
							
							to_file.delete();
						}
					}
				}
			}
    	}
    }
    
    
    
    public static void writeBytesAsFile( String filename, byte[] file_data ) {
      try{
        File file = new File( filename );
        
        FileOutputStream out = new FileOutputStream( file );
        
        out.write( file_data );
        
        out.close();
      }
      catch( Throwable t ) {
        Debug.out( "writeBytesAsFile:: error: ", t );
      }

    }
    
	public static boolean
	deleteWithRecycle(
		File		file )
	{
		if ( COConfigurationManager.getBooleanParameter("Move Deleted Data To Recycle Bin" )){
			
			try{
			    final PlatformManager	platform  = PlatformManagerFactory.getPlatformManager();
			    
			    if (platform.hasCapability(PlatformManagerCapabilities.RecoverableFileDelete)){
			    	
			    	platform.performRecoverableFileDelete( file.getAbsolutePath());
			    
			    	return( true );
			    	
			    }else{
			    	
			    	return( file.delete());
			    }
			}catch( PlatformManagerException e ){
				
				return( file.delete());
			}
		}else{
			
			return( file.delete());
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -