Java Code Examples for java.io.File#getName()

The following examples show how to use java.io.File#getName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JarFinder.java    From big-c with Apache License 2.0 6 votes vote down vote up
private static void zipDir(File dir, String relativePath, ZipOutputStream zos,
                           boolean start) throws IOException {
  String[] dirList = dir.list();
  for (String aDirList : dirList) {
    File f = new File(dir, aDirList);
    if (!f.isHidden()) {
      if (f.isDirectory()) {
        if (!start) {
          ZipEntry dirEntry = new ZipEntry(relativePath + f.getName() + "/");
          zos.putNextEntry(dirEntry);
          zos.closeEntry();
        }
        String filePath = f.getPath();
        File file = new File(filePath);
        zipDir(file, relativePath + f.getName() + "/", zos, false);
      }
      else {
        String path = relativePath + f.getName();
        if (!path.equals(JarFile.MANIFEST_NAME)) {
          ZipEntry anEntry = new ZipEntry(path);
          copyToZipStream(f, anEntry, zos);
        }
      }
    }
  }
}
 
Example 2
Source File: PackageSmallFilesThread.java    From FastCopy with Apache License 2.0 6 votes vote down vote up
private void fallbackToCopyFilesDirectly() {
	File[] files = new File(sSourceDir).listFiles();
	rdProUI.println(LogLevel.debug, "Fall back to copy files directly for dir:" + sSourceDir );
	if (files!=null) {
		for (File childFile : files) {

			if (RunTimeProperties.instance.isStopThreads()) {
				rdProUI.println("[PackageSmallFilesThread]\n" + Thread.currentThread().getName() + "is stopped.");
				return;
			}


			String newDestFile = sTargetDir + File.separator + childFile.getName();
			File targetFile = new File(newDestFile);
			if (!targetFile.exists() || FileUtils.overrideTargetFile(childFile, targetFile)) {
				CopyFileThread t = new CopyFileThread(rdProUI
						, childFile, targetFile, null, statistics);
				fileCopyWorkersPool.addTask(t);
			} else {
					rdProUI.println(LogLevel.debug, String.format("\tFile %s exists on the target dir, skipped. ", newDestFile));
			}
		}

	}

}
 
Example 3
Source File: SharedFolderWithWritePermissionDeleteTest.java    From Hive2Hive with MIT License 6 votes vote down vote up
@Test
public void testSynchronizeAddSubFileFromBDeleteFromA() throws NoSessionException, NoPeerConnectionException,
		IOException, IllegalArgumentException, IllegalArgumentException, GetFailedException {
	logger.info("Upload a new file 'folder1/subfolder/file1FromB' from B.");
	File subFile1FromBAtB = FileTestUtil.createFileRandomContent("file1FromB", new Random().nextInt(MAX_NUM_CHUNKS) + 1,
			subFolderB);
	UseCaseTestUtil.uploadNewFile(nodeB, subFile1FromBAtB);

	logger.info("Wait till new file 'folder1/subfolder/file1FromB' gets synchronized with A.");
	File subFile1FromBAtA = new File(subFolderA, subFile1FromBAtB.getName());
	waitTillSynchronized(subFile1FromBAtA, true);
	compareFiles(subFile1FromBAtA, subFile1FromBAtB);
	checkIndex(subFile1FromBAtA, subFile1FromBAtB, false);

	logger.info("Delete file 'folder1/subfolder/file1FromB' from A.");
	UseCaseTestUtil.deleteFile(nodeA, subFile1FromBAtA);

	logger.info("Wait till deletion of file 'folder1/subfolder/file1FromB' gets synchronized with B.");
	waitTillSynchronized(subFile1FromBAtB, false);
	checkIndex(subFile1FromBAtA, subFile1FromBAtB, true);
}
 
Example 4
Source File: SharedFolderWithWritePermissionMoveInternalTest.java    From Hive2Hive with MIT License 6 votes vote down vote up
@Test
public void testSynchronizeAddFolderFromBMoveToSubfolderAtB() throws NoSessionException, NoPeerConnectionException,
		IOException, IllegalArgumentException, IllegalArgumentException, GetFailedException {
	logger.info("Upload a new folder 'sharedfolder/subfolder2FromB' from B.");
	File folderFromBAtB = new File(sharedFolderB, "subfolder2FromB");
	folderFromBAtB.mkdir();
	UseCaseTestUtil.uploadNewFile(network.get(1), folderFromBAtB);

	logger.info("Wait till new folder 'sharedFolder/subfolder2FromB' gets synchronized with A.");
	File folderFromBAtA = new File(sharedFolderB, folderFromBAtB.getName());
	waitTillSynchronized(folderFromBAtA, true);

	logger.info("Move folder 'subfolder2FromB' at B into shared subfolder 'sharedfolder/subfolder1'.");
	File movedFolderFromBAtB = new File(subFolder1AtB, folderFromBAtB.getName());
	FileUtils.moveDirectory(folderFromBAtB, movedFolderFromBAtB);
	UseCaseTestUtil.moveFile(network.get(1), folderFromBAtB, movedFolderFromBAtB);

	logger.info("Wait till moved folder 'subfolderFromB' gets synchronized with A.");
	File movedFolderFromBAtA = new File(subFolder1AtA, folderFromBAtA.getName());
	waitTillSynchronized(movedFolderFromBAtA, true);
	compareFiles(movedFolderFromBAtA, movedFolderFromBAtB);
	checkIndex(folderFromBAtA, folderFromBAtB, movedFolderFromBAtA, movedFolderFromBAtB);
}
 
Example 5
Source File: DiscUtil.java    From IridiumSkyblock with GNU General Public License v2.0 6 votes vote down vote up
public static void writeCatch(final File file, final String content) {
    String name = file.getName();
    final Lock lock;

    // Create lock for each file if there isn't already one.
    if (locks.containsKey(name)) {
        lock = locks.get(name);
    } else {
        ReadWriteLock rwl = new ReentrantReadWriteLock();
        lock = rwl.writeLock();
        locks.put(name, lock);
    }
    lock.lock();
    try {
        file.createNewFile();
        Files.write(content, file, StandardCharsets.UTF_8);
    } catch (IOException e) {
        IridiumSkyblock.getInstance().sendErrorMessage(e);
    } finally {
        lock.unlock();
    }
}
 
Example 6
Source File: SharedFolderWithReadPermissionMoveInternalTest.java    From Hive2Hive with MIT License 6 votes vote down vote up
@Test
public void testSynchronizeAddSubFileAtAMoveToSubfolderAtA() throws NoSessionException, NoPeerConnectionException,
		IOException, IllegalArgumentException, IllegalArgumentException, GetFailedException {
	File fileFromAAtA = FileTestUtil.createFileRandomContent("subfile3FromA", new Random().nextInt(MAX_NUM_CHUNKS) + 1,
			subFolder1A);
	logger.info("Upload a new file '{}' at A.", fileFromAAtA.getName());
	UseCaseTestUtil.uploadNewFile(nodeA, fileFromAAtA);

	logger.info("Wait till new file '{}' gets synchronized with B.", fileFromAAtA.getName());
	File fileFromAAtB = new File(subFolder1B, fileFromAAtA.getName());
	waitTillSynchronized(fileFromAAtB, true);

	File movedFileFromAAtA = new File(subFolder2A, fileFromAAtA.getName());
	logger.info("Move file '{}' at A into shared subfolder '{}'.", fileFromAAtA.getName(), subFolder2A);
	FileUtils.moveFile(fileFromAAtA, movedFileFromAAtA);
	UseCaseTestUtil.moveFile(nodeA, fileFromAAtA, movedFileFromAAtA);

	logger.info("Wait till new moved file '{}' gets synchronized with B.", fileFromAAtA.getName());
	File movedFileFromAAtB = new File(subFolder2B, fileFromAAtA.getName());
	waitTillSynchronized(movedFileFromAAtB, true);
	compareFiles(movedFileFromAAtA, movedFileFromAAtB);
	checkIndexAfterMoving(fileFromAAtA, fileFromAAtB, movedFileFromAAtA, movedFileFromAAtB);
}
 
Example 7
Source File: RepoGen.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
private void createJar(final File jarFile, final File[] files) throws IOException
{
	final Manifest manifest = new Manifest();
	final Attributes attributes = manifest.getMainAttributes();
	attributes.putValue("Manifest-Version", "1.0");
	attributes.putValue("Created-By", "RepoGen 1.0.0");
	final FileOutputStream fos = new FileOutputStream(jarFile);
	final JarOutputStream jos = new JarOutputStream(fos, manifest);
	for (final File file : files)
	{
		final ZipEntry entry = new ZipEntry(file.getName());
		jos.putNextEntry(entry);
		final FileInputStream fis = new FileInputStream(file);
		pipeStream(fis, jos);
		fis.close();
	}
	jos.close();
}
 
Example 8
Source File: JSONPdxClientServerDUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public static byte[] getBytesFromFile(String fileName) throws IOException {
  File file = new File(fileName);
  
  java.io.InputStream is = new FileInputStream(file);

   // Get the size of the file
   long length = file.length();

   // Create the byte array to hold the data
   byte[] bytes = new byte[(int)length];

   // Read in the bytes
   int offset = 0;
   int numRead = 0;
   while (offset < bytes.length
          && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
       offset += numRead;
   }

   // Ensure all the bytes have been read in
   if (offset < bytes.length) {
       throw new IOException("Could not completely read file "+file.getName());
   }
  
   is.close();
   return bytes;
}
 
Example 9
Source File: WZFile.java    From HeavenMS with GNU Affero General Public License v3.0 5 votes vote down vote up
public WZFile(File wzfile, boolean provideImages) throws IOException {
    this.wzfile = wzfile;
    lea = new GenericLittleEndianAccessor(new InputStreamByteStream(new BufferedInputStream(new FileInputStream(wzfile))));
    RandomAccessFile raf = new RandomAccessFile(wzfile, "r");
    slea = new GenericSeekableLittleEndianAccessor(new RandomAccessByteStream(raf));
    root = new WZDirectoryEntry(wzfile.getName(), 0, 0, null);
    this.provideImages = provideImages;
    load();
}
 
Example 10
Source File: AbstractCommandLineRunner.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the path at which to output map file(s) based on the path at which
 * the JS binary will be placed.
 *
 * @return The path in which to place the generated map file(s).
 */
private String getMapPath(String outputFile) {
  String basePath = "";

  if (outputFile.equals("")) {
    // If we have a js_module_binary rule, output the maps
    // at modulename_props_map.out, etc.
    if (!config.moduleOutputPathPrefix.equals("")) {
      basePath = config.moduleOutputPathPrefix;
    } else {
      basePath = "jscompiler";
    }
  } else {
    // Get the path of the output file.
    File file = new File(outputFile);

    String outputFileName = file.getName();

    // Strip the .js from the name.
    if (outputFileName.endsWith(".js")) {
      outputFileName =
          outputFileName.substring(0, outputFileName.length() - 3);
    }

    basePath = file.getParent() + File.separatorChar + outputFileName;
  }

  return basePath;
}
 
Example 11
Source File: Uploader.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Adds a upload file section to the request
 *
 * @param fieldName name attribute in <input type="file" name="..." />
 * @param uploadFile a File to be uploaded
 * @throws IOException
 */
public void addFilePart(String fieldName, File uploadFile)
        throws IOException {
    String fileName = uploadFile.getName();
    writer.append("--" + boundary).append(LINE_FEED);
    writer.append(
            "Content-Disposition: form-data; name=\"" + fieldName
            + "\"; filename=\"" + fileName + "\"")
            .append(LINE_FEED);
    writer.append(
            "Content-Type: "
            + URLConnection.guessContentTypeFromName(fileName))
            .append(LINE_FEED);
    writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
    writer.append(LINE_FEED);
    writer.flush();

    FileInputStream inputStream = new FileInputStream(uploadFile);
    byte[] buffer = new byte[4096];
    int bytesRead = -1;
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
    }
    outputStream.flush();
    inputStream.close();

    writer.append(LINE_FEED);
    writer.flush();
}
 
Example 12
Source File: GNPSUtils.java    From mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Submit feature-based molecular networking (FBMN) job to GNPS
 * 
 * @param file
 * @param param
 * @return
 */
public static String submitFbmnJob(File file, GnpsFbmnSubmitParameters param) throws IOException {
  // optional
  boolean useMeta = param.getParameter(GnpsFbmnSubmitParameters.META_FILE).getValue();
  boolean openWebsite = param.getParameter(GnpsFbmnSubmitParameters.OPEN_WEBSITE).getValue();
  String presets = param.getParameter(GnpsFbmnSubmitParameters.PRESETS).getValue().toString();
  String title = param.getParameter(GnpsFbmnSubmitParameters.JOB_TITLE).getValue();
  String email = param.getParameter(GnpsFbmnSubmitParameters.EMAIL).getValue();
  String username = param.getParameter(GnpsFbmnSubmitParameters.USER).getValue();
  String password = param.getParameter(GnpsFbmnSubmitParameters.PASSWORD).getValue();
  //
  File folder = file.getParentFile();
  String name = file.getName();
  // all file paths
  File mgf = FileAndPathUtil.getRealFilePath(folder, name, "mgf");
  File quan = FileAndPathUtil.getRealFilePath(folder, name + "_quant", "csv");

  // NEEDED files
  if (mgf.exists() && quan.exists()) {
    File meta = !useMeta ? null
        : param.getParameter(GnpsFbmnSubmitParameters.META_FILE).getEmbeddedParameter()
            .getValue();

    return submitFbmnJob(mgf, quan, meta, null, title, email, username, password, presets,
        openWebsite);
  } else
    return "";
}
 
Example 13
Source File: MultiFileUnixCommandPlace.java    From emissary with Apache License 2.0 5 votes vote down vote up
/**
 * Process in a custom way when there is only one file result
 * 
 * @param d the parent payload
 * @param theData the bytes to process
 * @param f the file the data comes from
 * @return 0 when it works
 */
protected int processSingleChild(IBaseDataObject d, byte[] theData, File f) {
    String filename = f.getName();
    d.setData(theData);
    if (setTitleToFile) {
        d.putParameter("DocumentTitle", filename);
    }
    List<String> tmpForms = getFormsFromFile(f);
    for (int i = 0; i < tmpForms.size(); i++) {
        d.pushCurrentForm(tmpForms.get(i));
    }
    d.setFileType(SINGLE_CHILD_FILETYPE);
    return (0);
}
 
Example 14
Source File: NameItem.java    From BiglyBT with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void
refresh(
	TableCell 	cell,
	boolean 	sortOnlyRefresh)
{
	DownloadStubFile fileInfo = (DownloadStubFile) cell.getDataSource();

	String name;

	if ( fileInfo == null ){

		name = "";

	}else{

		File f = fileInfo.getFile();

		if ( show_full_path ){

			name = f.getAbsolutePath();
		}else{

			name = f.getName();
		}
	}

	cell.setText(name);
}
 
Example 15
Source File: ReflectionUtil.java    From ApkTrack with GNU General Public License v3.0 5 votes vote down vote up
public static List<String> getSourcePaths(Context context) throws PackageManager.NameNotFoundException, IOException {
    ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0);
    File sourceApk = new File(applicationInfo.sourceDir);
    File dexDir = new File(applicationInfo.dataDir, SECONDARY_FOLDER_NAME);

    List<String> sourcePaths = new ArrayList<String>();
    //default apk path
    sourcePaths.add(applicationInfo.sourceDir);

    String extractedFilePrefix = sourceApk.getName() + EXTRACTED_NAME_EXT;

    //get the dex number
    int totalDexNumber = getMultiDexPreferences(context).getInt(KEY_DEX_NUMBER, 1);

    //get other dexes
    for (int i = 2; i <= totalDexNumber; i++) {
        String fileName = extractedFilePrefix + i + EXTRACTED_SUFFIX;
        File extractedFile = new File(dexDir, fileName);
        if (extractedFile.isFile()) {
            sourcePaths.add(extractedFile.getAbsolutePath());
        } else {
            throw new IOException("Missing extracted secondary dex file '" +
                    extractedFile.getPath() + "'");
        }
    }

    return sourcePaths;
}
 
Example 16
Source File: ManClassUtil.java    From manifold with Apache License 2.0 4 votes vote down vote up
public static String getFileExtension( File file )
{
  String name = file.getName();
  return getFileExtension( name );
}
 
Example 17
Source File: TextFileBackuper.java    From netbeans-mmd-plugin with Apache License 2.0 4 votes vote down vote up
@Nonnull
public static String makeBackupFileName(@Nonnull final File orig, final int index) {
  final String name = orig.getName();
  return String.format(".%s.%d.abk", name, index);
}
 
Example 18
Source File: FileHelper.java    From OmniList with GNU Affero General Public License v3.0 4 votes vote down vote up
public static File getExternalFilesBackupDir(File backupDir) {
    File attachmentsDir = FileHelper.getAttachmentDir(PalmApp.getContext());
    return new File(backupDir, attachmentsDir.getName());
}
 
Example 19
Source File: ProBamFileImport.java    From PDV with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Constructor
 * @param pdvMainClass Parent class
 * @param proBAMFile ProBAM file
 * @param spectrumFileName Spectrum file name
 * @param spectrumFactory Spectrum factory
 * @param progressDialog Progress dialog
 * @throws SQLException
 * @throws ClassNotFoundException
 */
public ProBamFileImport(PDVMainClass pdvMainClass, File proBAMFile, String spectrumFileName, String spectrumFileType, SpectrumFactory spectrumFactory, ProgressDialogX progressDialog) throws SQLException, ClassNotFoundException {
    this.pdvMainClass = pdvMainClass;
    this.proBAMFile = proBAMFile;
    this.spectrumFactory = spectrumFactory;
    this.progressDialog = progressDialog;
    this.spectrumFileType = spectrumFileType;
    this.spectrumFileName = spectrumFileName;

    scoreName.add("Score");
    scoreName.add("FDR");
    scoreName.add("isAnnotated");
    scoreName.add("followingAA");
    scoreName.add("precedingAA");
    scoreName.add("enzyme");
    scoreName.add("peptideType");
    scoreName.add("geneMapNum");
    scoreName.add("peptideInt");
    scoreName.add("peptideMapNum");
    scoreName.add("missedCNum");
    scoreName.add("uniqueType");
    scoreName.add("originalSeq");
    scoreName.add("enzymeInSearch");
    scoreName.add("URI");

    String dbName = proBAMFile.getParentFile().getAbsolutePath()+"/"+ proBAMFile.getName()+".db";

    File dbFile = new File(dbName);
    File dbJournalFile = new File(dbName + "-journal");
    if (dbFile.isFile() && dbFile.exists()) {
        dbFile.delete();
    }
    if (dbJournalFile.isFile() && dbJournalFile.exists()) {
        dbJournalFile.delete();
    }

    sqLiteConnection = new SQLiteConnection(dbName);

    sqLiteConnection.setScoreNum(15);

    new Thread("DisplayThread") {
        @Override
        public void run() {
            try {
                parseProBAM();

                pdvMainClass.searchButton.setEnabled(true);
            } catch (Exception e) {
                progressDialog.setRunFinished();
                JOptionPane.showMessageDialog(
                        null, "Failed to parse proBAM file, please check your file.",
                        "Error Parsing File", JOptionPane.ERROR_MESSAGE);
                e.printStackTrace();
            }
        }
    }.start();
}
 
Example 20
Source File: FrameworkGenerator.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
private static String extractFrameworkNameFrom(final File file) {
    final String fileName = file.getName();
    return fileName.substring(0, fileName.lastIndexOf(BRIDGESUPPORT_FILE_EXTENSION));
}