org.openide.filesystems.FileUtil.findFreeFileName()方法的使用及代码示例

x33g5p2x  于2022-01-19 转载在 其他  
字(13.4k)|赞(0)|评价(0)|浏览(71)

本文整理了Java中org.openide.filesystems.FileUtil.findFreeFileName()方法的一些代码示例,展示了FileUtil.findFreeFileName()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。FileUtil.findFreeFileName()方法的具体详情如下:
包路径:org.openide.filesystems.FileUtil
类名称:FileUtil
方法名:findFreeFileName

FileUtil.findFreeFileName介绍

[英]Finds an unused file name similar to that requested in the same folder. The specified file name is used if that does not yet exist or is FileObject#isVirtual. Otherwise, the first available name of the form basename_nnn.ext (counting from one) is used.

Caution: this method does not lock the parent folder to prevent race conditions: i.e. it is possible (though unlikely) that the resulting name will have been created by another thread just as you were about to create the file yourself (if you are, in fact, intending to create it just after this call). Since you cannot currently lock a folder against child creation actions, the safe approach is to use a loop in which a free name is retrieved; an attempt is made to FileObject#createDatathat file; and upon an IOException during creation, retry the loop up to a few times before giving up.
[中]查找与同一文件夹中请求的文件名相似的未使用文件名。如果指定的文件名尚不存在或是FileObject#isVirtual,则使用该文件名。否则,将使用表格basename_nnn.ext(从一开始计算)的第一个可用名称。
*警告:*此方法不会锁定父文件夹以防止竞争条件:即,结果名称可能(尽管不太可能)是由另一个线程创建的,正如您将要自己创建文件一样(如果您实际上打算在调用之后创建文件)。由于当前无法针对子创建操作锁定文件夹,因此安全的方法是使用一个循环,在该循环中检索自由名称;试图将FileObject#Createdata复制到该文件;在创建过程中遇到IOException错误时,请在放弃之前重试循环几次。

代码示例

代码示例来源:origin: org.netbeans.modules/org-netbeans-modules-visualweb-palette

public static String getFreeFileName(FileObject folder, String filename, String nameExt) {
    String myfilename = filename.replaceAll("\\W", "");
    return FileUtil.findFreeFileName(folder, myfilename, nameExt);
  }
}

代码示例来源:origin: nl.cloudfarming.client/field-project

@Override
  public Transferable paste() throws IOException {
    FileObject fieldsFolder = getLookup().lookup(FileObject.class);
    String name = FileUtil.findFreeFileName(fieldsFolder, field.getName(), Field.EXT);
    LOGGER.log(Level.FINEST, "found free filename: {0}", name);
    FileObject fieldFile = fieldsFolder.createData(name, Field.EXT);
    FieldManager fieldManager = Lookup.getDefault().lookup(FieldManager.class);
    fieldManager.save(field, fieldFile);
    return null;
  }
};

代码示例来源:origin: net.sf.squirrel-sql.thirdparty-non-maven/openide-loaders

public void run () throws IOException {
    String fileName;
    if (name == null) {
      fileName = FileUtil.findFreeFileName(
        fo, className.replace ('.', '-'), INSTANCE);
    } else {
      fileName = escape(name);
    }
    fos[0] = fo.createData (fileName, INSTANCE);
    fos[0].setAttribute(EA_INSTANCE_CLASS, className);
  }
});

代码示例来源:origin: net.sf.squirrel-sql.thirdparty-non-maven/openide-loaders

public void run () throws IOException {
  FileObject fo = folder.getPrimaryFile ();
  String filename = name;
  if (filename == null) {
    filename = instance.getClass().getName().replace ('.', '-');
    filename = FileUtil.findFreeFileName(fo, filename, XML_EXT);
  } else {
    String escapedFileName = escape(filename);
    // do not cut if such file already exist
    FileObject newFile = fo.getFileObject (escapedFileName, XML_EXT);
    if (newFile == null) {
      filename = escapeAndCut(filename);
    } else {
      filename = escapedFileName;
    }
    
    if (create /*|| (newFile == null && Utilities.isWindows()) */) {
      filename = FileUtil.findFreeFileName(fo, filename, XML_EXT);
    }
  }
  result = storeSettings(folder, filename, instance, mi);
}

代码示例来源:origin: org.netbeans.modules/org-netbeans-modules-performance

private synchronized void stop(int round) throws Exception {
  ActionListener ss = (ActionListener) profiler;
  profiler = null;
  if (!profiling) {
    return;
  }
  FileObject wd = FileUtil.toFileObject(getWorkDir());
  String n = FileUtil.findFreeFileName(wd, "snapshot-" + round, "nps"); // NOI18N
  FileObject snapshot = wd.createData(n, "nps"); // NOI18N
  DataOutputStream dos = new DataOutputStream(snapshot.getOutputStream());
  ss.actionPerformed(new ActionEvent(dos, 0, "write")); // NOI18N
  dos.close();
  LOG.log(
      Level.WARNING, "Profiling snapshot taken into {0}", snapshot.getPath()
  );
}

代码示例来源:origin: net.sf.squirrel-sql.thirdparty-non-maven/openide-loaders

/** Check if in specific folder exists fileobject with the same name.
* If it exists user is asked for confirmation to rewrite, rename or cancel operation.
* @param folder destination folder
* @return the suffix which should be added to the name or null if operation is cancelled
*/
private String existInFolder(FileObject fo, FileObject folder) {
  // merge folders when neccessary
  if (fo.isFolder () && isMergingFolders ())
    return ""; // NOI18N
  
  String orig = fo.getName ();
  String name = FileUtil.findFreeFileName(
           folder, orig, fo.getExt ()
         );
  if (name.length () <= orig.length ()) {
    return ""; // NOI18N
  } else {
    return name.substring (orig.length ());
  }
}

代码示例来源:origin: org.netbeans.api/org-netbeans-modules-performance

private synchronized void stop(int round) throws Exception {
  ActionListener ss = (ActionListener) profiler;
  profiler = null;
  if (!profiling) {
    return;
  }
  FileObject wd = FileUtil.toFileObject(getWorkDir());
  String n = FileUtil.findFreeFileName(wd, "snapshot-" + round, "nps"); // NOI18N
  FileObject snapshot = wd.createData(n, "nps"); // NOI18N
  DataOutputStream dos = new DataOutputStream(snapshot.getOutputStream());
  ss.actionPerformed(new ActionEvent(dos, 0, "write")); // NOI18N
  dos.close();
  LOG.log(
      Level.WARNING, "Profiling snapshot taken into {0}", snapshot.getPath()
  );
}

代码示例来源:origin: org.netbeans.modules/org-netbeans-modules-web-jsf-navigation

public void actionPerformed(ActionEvent e) {
  try {
    final PageFlowController pfc = scene.getPageFlowView().getPageFlowController();
    
    final FileObject webFileObject = pfc.getWebFolder();
    
    String name = FileUtil.findFreeFileName(webFileObject, "page", "jsp");
    name = JOptionPane.showInputDialog("Select Page Name", name);
    
    createIndexJSP(webFileObject, name);
  } catch (IOException ex) {
    Exceptions.printStackTrace(ex);
  }
  
  //            }
}

代码示例来源:origin: org.netbeans.modules/org-netbeans-modules-web-jsf-navigation

public void actionPerformed(ActionEvent e) {
  //            This would work if we wanted to use the wizard.
  //            Action newFileAction = CommonProjectActions.newFileAction();
  //            JOptionPane.showMessageDialog(null, "Source: " + e.getSource());
  Object obj = e.getSource();
  if (obj instanceof PageFlowScene) {
    try {
      scene = (PageFlowScene) obj;
      PageFlowController pfc = scene.getPageFlowView().getPageFlowController();
      FileObject webFileObject = pfc.getWebFolder();
      String name = FileUtil.findFreeFileName(webFileObject, "Templates/JSP_Servlet/JSP.jsp", "jsp");
      name = JOptionPane.showInputDialog("Select Page Name", name);
      createIndexJSP(webFileObject, name);
    } catch (IOException ex) {
      Exceptions.printStackTrace(ex);
    }
  }
}

代码示例来源:origin: nl.cloudfarming.client/field-project

/**
 * Copy sourcefiles to import-folder
 * @param dataObject 
 */
@Override
public void importSources(DataObject dataObject) {
  FileObject importFolder = getImportFolder(true);
  
  Iterator<FileObject> files = dataObject.files().iterator();     
  while(files.hasNext()){
    FileObject current = files.next();
    try {
      String newFileName = FileUtil.findFreeFileName(importFolder, current.getName(), current.getExt());
      FileUtil.copyFile(current, importFolder, newFileName);
    } catch (IOException ex) {
      Exceptions.printStackTrace(ex);
    }
  }
}

代码示例来源:origin: nl.cloudfarming.client/import

/**
 * Copies the specified fileObject to the specified targetFolder. Tries to
 * get a free filename for the file object
 *
 * @param targetFolder the folder the fileObject must be copied to
 * @param toCopy the file to be copied
 * @return the copied fileObject or null if it could not be copied
 */
private FileObject copy(FileObject targetFolder, FileObject toCopy) {
  try {
    String newFileName = FileUtil.findFreeFileName(targetFolder, toCopy.getName(), toCopy.getExt());
    return FileUtil.copyFile(toCopy, targetFolder, newFileName);
  } catch (IOException ex) {
    LOGGER.log(Level.SEVERE, "Could not copy file {0} with the exception {1}", new Object[]{toCopy.getName(), ex});
  }
  return null;
}

代码示例来源:origin: net.sf.squirrel-sql.thirdparty-non-maven/openide-loaders

public Object run () throws IOException {
    FileObject fo;
    if (trg.isData ()) {
      fo = trg;
    } else {
       String n;
       if (name == null) {
         // #45810 - if obj is disk root then fix the filename
         String baseName = obj.getName().replace(':', '_').replace('/', '_'); // NOI18N
         n = FileUtil.findFreeFileName (trg, baseName, ext);
       } else {
         n = name;
       }
       fo = trg.createData (n, ext);
    }
    writeShadowFile(fo, obj.getPrimaryFile().getURL());
    return fo;
  }
});

代码示例来源:origin: eu.agrosense.client/import

/**
 * Copies the specified FileObject to the specified targetFolder.
 * 
 * <p>
 * Tries to get a free filename for the file object</p>
 *
 * @param targetFolder the folder the fileObject must be copied to
 * @param toCopy the file to be copied
 * @return the copied fileObject or null if it could not be copied
 */
private FileObject copy(FileObject targetFolder, FileObject toCopy) {
  try {
    String newFileName = FileUtil.findFreeFileName(targetFolder, toCopy.getName(), toCopy.getExt());
    return FileUtil.copyFile(toCopy, targetFolder, newFileName);
  } catch (IOException ex) {
    LOGGER.log(Level.SEVERE, "Could not copy file {0} with the exception {1}", new Object[]{toCopy.getName(), ex});
  }
  return null;
}

代码示例来源:origin: org.netbeans.modules/org-netbeans-modules-profiler

private String getCurrentHeapDumpFilename(String targetFolder) {
  try {
    String fileName = ResultsManager.getDefault().getDefaultHeapDumpFileName(System.currentTimeMillis());
    FileObject folder = (targetFolder == null)
              ? ProjectStorage.getSettingsFolder(NetBeansProfiler.getDefaultNB().getProfiledProject(), true)
              : FileUtil.toFileObject(FileUtil.normalizeFile(new File(targetFolder)));
    return FileUtil.toFile(folder).getAbsolutePath() + File.separator
        + FileUtil.findFreeFileName(folder, fileName, ResultsManager.HEAPDUMP_EXTENSION) + "."
        + ResultsManager.HEAPDUMP_EXTENSION; // NOI18N
  } catch (IOException e) {
    return null;
  }
}

代码示例来源:origin: nl.cloudfarming.client/field-project

@Override
public void importShapes(List<Shape> shapes) {
  FileObject fieldsFolder = getFieldsFolder(true);
  for (Shape shape : shapes) {
    // Create field from shape
    Field field = new Field();
    field.setGeometry(shape.getGeometry());
    field.setName(shape.getName());
    
    try {
      String name = FileUtil.findFreeFileName(fieldsFolder, field.getName(), Field.EXT);
      LOGGER.log(Level.FINEST, "found free filename: {0}", name);
      FileObject fieldFile;
      fieldFile = fieldsFolder.createData(name, Field.EXT);
      FieldManager fieldManager = Lookup.getDefault().lookup(FieldManager.class);
      fieldManager.save(field, fieldFile);
    } catch (IOException ex) {
      Exceptions.printStackTrace(ex);
    }
  }
}

代码示例来源:origin: net.sf.squirrel-sql.thirdparty-non-maven/openide-loaders

/** Creates shadow for this object in specified folder (overridable in subclasses).
 * <p>The default
* implementation creates a reference data shadow and pastes it into
* the specified folder.
*
* @param f the folder to create a shortcut in
* @return the shadow
*/
protected DataShadow handleCreateShadow (DataFolder f) throws IOException {
  // #33871 - prevent creation of recursive folder structure
  testNesting(this, f);
  
  String name;
  if (getPrimaryFile ().isRoot ()) {
    name = FileUtil.findFreeFileName (
          f.getPrimaryFile (), ROOT_SHADOW_NAME, DataShadow.SHADOW_EXTENSION
        );
  } else {
    name = null;
  }
  return DataShadow.create (f, name, this);
}

代码示例来源:origin: net.sf.squirrel-sql.thirdparty-non-maven/openide-loaders

protected DataObject handleCreateFromTemplate (
  DataFolder df, String name
) throws IOException {
  FileObject fo;
  if (name == null) {
    name = FileUtil.findFreeFileName(
          df.getPrimaryFile (), getPrimaryFile ().getName (), getPrimaryFile ().getExt ()
        );
  }
  fo = getPrimaryEntry().createFromTemplate (df.getPrimaryFile (), name);
  Iterator it = secondaryEntries().iterator();
  while (it.hasNext ()) {
    ((Entry)it.next()).createFromTemplate (df.getPrimaryFile (), name);
  }
  
  try {
    return createMultiObject (fo);
  } catch (DataObjectExistsException ex) {
    return ex.getDataObject ();
  }
}

代码示例来源:origin: net.sf.squirrel-sql.thirdparty-non-maven/openide-loaders

public FileObject createFromTemplate (FileObject f, String name) throws IOException {
  if (name == null) {
    name = FileUtil.findFreeFileName(
          f,
          getFile ().getName (), getFile ().getExt ()
        );
  }
  FileObject fo = getFile().copy (f, name, getFile().getExt ());
  // unmark template state
  DataObject.setTemplate (fo, false);
  return fo;
}

代码示例来源:origin: net.sf.squirrel-sql.thirdparty-non-maven/openide-loaders

/** Creates new folder and copies attributes, the template flag is cleared.
 * @param f the folder to create this entry in
 * @param name the new name to use
 * @return the copied <code>FileObject</code> or <code>null</code> if it cannot be copied
 * @exception IOException when the operation fails
 */
public FileObject createFromTemplate (FileObject f, String name) throws IOException {
  if (name == null) {
    name = FileUtil.findFreeFileName(
          f,
          getFile ().getName (), getFile ().getExt ()
        );
  }
  FileObject fo = FileUtil.createFolder (f, name);
  FileUtil.copyAttributes (getFile (), fo);
  DataObject.setTemplate (fo, false);
  return fo;
}

代码示例来源:origin: org.netbeans.modules/org-netbeans-modules-j2ee-jboss4

private static void register(FileObject serverInstanceDir, String serverLocation, String domainLocation, String host, String port) throws IOException {
  String displayName = generateDisplayName(serverInstanceDir);
  String url = URI_PREFIX + host + ":" + port + "#default&" + serverLocation;    // NOI18N
  String name = FileUtil.findFreeFileName(serverInstanceDir, "instance", null); // NOI18N
  FileObject instanceFO = serverInstanceDir.createData(name);
  instanceFO.setAttribute(InstanceProperties.URL_ATTR, url);
  instanceFO.setAttribute(InstanceProperties.USERNAME_ATTR, "");
  instanceFO.setAttribute(InstanceProperties.PASSWORD_ATTR, "");
  instanceFO.setAttribute(InstanceProperties.DISPLAY_NAME_ATTR, displayName);
  instanceFO.setAttribute(InstanceProperties.REMOVE_FORBIDDEN, "true");
  instanceFO.setAttribute(JBPluginProperties.PROPERTY_SERVER, "default"); // NOI18N
  String deployDir = JBPluginUtils.getDeployDir(domainLocation);
  instanceFO.setAttribute(JBPluginProperties.PROPERTY_DEPLOY_DIR, deployDir);
  instanceFO.setAttribute(JBPluginProperties.PROPERTY_SERVER_DIR, domainLocation);
  instanceFO.setAttribute(JBPluginProperties.PROPERTY_ROOT_DIR, serverLocation);
  instanceFO.setAttribute(JBPluginProperties.PROPERTY_HOST, host);
  instanceFO.setAttribute(JBPluginProperties.PROPERTY_PORT, port);
}

相关文章

微信公众号

最新文章

更多