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

📄 fileutil.java

📁 这是一个基于java编写的torrent的P2P源码
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
    		FileUtil.mkdirs(new_parent);
    		
    		for (int i=0;i<files.length;i++){
    			
    			File	from_file	= files[i];
    			
    			copyFileOrDirectory( from_file, new_parent );
    		}
    	}else{
    		
    		copyFile(  from_file_or_dir, new File( to_parent_dir, from_file_or_dir.getName()));
    	}
    }
    
    /**
     * 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 )
    {
        return renameFile(from_file, to_file, true);
    	}
    	

    public static boolean
    renameFile(
        File        from_file,
        File        to_file,
        boolean     fail_on_existing_directory)
    {
    	return renameFile(from_file, to_file, fail_on_existing_directory, null);
    }
    
    public static boolean renameFile(
    	File        from_file,
    	File        to_file,
    	boolean     fail_on_existing_directory,
    	FileFilter  file_filter
    ) {
    
    	if ( !from_file.exists()){
    		Logger
					.log(new LogAlert(LogAlert.REPEATABLE, LogAlert.AT_ERROR,
							"renameFile: source file '" + from_file
									+ "' doesn't exist, failing"));
    		
    		return( false );
    	}
    	
        /**
         * If the destination exists, we only fail if requested.
         */
        if (to_file.exists() && (fail_on_existing_directory || from_file.isFile() || to_file.isFile())) {
            Logger.log(new LogAlert(LogAlert.REPEATABLE, LogAlert.AT_ERROR,
                    "renameFile: target file '" + to_file + "' already exists, failing"));

            return( false );
        }
    	File to_file_parent = to_file.getParentFile();
    	if (!to_file_parent.exists()) {FileUtil.mkdirs(to_file_parent);}
    	
    	if ( from_file.isDirectory()){
    		
    		File[] files = null;
    		if (file_filter != null) {files = from_file.listFiles(file_filter);}
    		else {files = from_file.listFiles();}
    		
    		if ( files == null ){
    			
    				// empty dir
    			
    			return( true );
    		}
    		
    		int	last_ok = 0;
    		
    		if (!to_file.exists()) {to_file.mkdir();}
    		
    		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, fail_on_existing_directory, file_filter )){
    					
    					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 ){
    				// This might be important or not. We'll make it a debug message if we had a filter,
    				// or log it normally otherwise.
    				if (file_filter == null) {
    					Logger.log(new LogAlert(LogAlert.REPEATABLE, LogAlert.AT_ERROR,
							"renameFile: files remain in '" + from_file.toString()
									+ "', not deleting"));
    				}
    				else {
    					/* Should we log this? How should we log this? */
    					return true;
    				}
   				 
    			}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{
    				// null - We don't want to use the file filter, it only refers to source paths.
                    if ( !renameFile( tf, ff, false, null )){
    					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());
		}
	}
	
	public static String translateMoveFilePath(String old_root, String new_root, String file_to_move) {
		if (!file_to_move.startsWith(old_root)) {return null;}
		String file_suffix = file_to_move.substring(old_root.length());
		if (new_root.endsWith(File.separator)) {new_root = new_root.substring(0, new_root.length()-1);}
		if (file_suffix.startsWith(File.separator)) {file_suffix = file_suffix.substring(1);}
		return new_root + File.separator + file_suffix;
	}
	
	public static void
	runAsTask(
		AzureusCoreOperationTask	task )
	{
		AzureusCore	core = AzureusCoreFactory.getSingleton();
		
		core.createOperation( AzureusCoreOperation.OP_FILE_MOVE, task );
	}
	
	public static boolean mkdirs(File f) {
		if (Constants.isOSX) {
			Pattern pat = Pattern.compile("^(/Volumes/[^/]+)");
			Matcher matcher = pat.matcher(f.getParent());
			if (matcher.find()) {
				String sVolume = matcher.group();
				File fVolume = new File(sVolume);
				if (!fVolume.isDirectory()) {
					Logger.log(new LogEvent(LOGID, LogEvent.LT_WARNING, sVolume
							+ " is not mounted or not available."));
					return false;
				}
			}
		}
		return f.mkdirs();
	}
	
	public static String getExtension(String fName) {
		final int fileSepIndex = fName.lastIndexOf(File.separator);
		final int fileDotIndex = fName.lastIndexOf('.');
		if (fileSepIndex == fName.length() - 1 || fileDotIndex == -1
				|| fileSepIndex > fileDotIndex) {
			return "";
		}
		
		return fName.substring(fileDotIndex);
	}
	
	public static String
	readFileAsString(
		File	file,
		int		size_limit )
	
		throws IOException
	{
		FileInputStream fis = new FileInputStream(file);
		try {
			return readInputStreamAsString(fis, size_limit);
		} finally {

			fis.close();
		}
	}
		
	public static String
	readInputStreamAsString(
		InputStream is,
		int		size_limit )
	
		throws IOException
	{
		StringBuffer result = new StringBuffer(1024);

		byte[] buffer = new byte[1024];

		while (true) {

			int len = is.read(buffer);

			if (len <= 0) {

				break;
			}

			result.append(new String(buffer, 0, len, "ISO-8859-1"));

			if (size_limit >= 0 && result.length() > size_limit) {

				result.setLength(size_limit);

				break;
			}
		}

		return (result.toString());
	}

	public static String
	readFileEndAsString(
		File	file,
		int		size_limit )
	
		throws IOException
	{
		FileInputStream	fis = new FileInputStream( file );
		
		try{
			if (file.length() > size_limit) {
				fis.skip(file.length() - size_limit);
			}
			
			StringBuffer	result = new StringBuffer(1024);
			
			byte[]	buffer = new byte[1024];
			
			while( true ){
			
				int	len = fis.read( buffer );
			
				if ( len <= 0 ){
					
					break;
				}
			
				result.append( new String( buffer, 0, len, "ISO-8859-1" ));
				
				if ( result.length() > size_limit ){
					
					result.setLength( size_limit );
					
					break;
				}
			}
			
			return( result.toString());
			
		}finally{
			
			fis.close();
		}
	}
}

⌨️ 快捷键说明

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