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

The following are Jave code examples for showing how to use getName() of the java.io.File class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: dshell   File: DefaultDependencyResolver.java   View Source Code Vote up 6 votes
/**
 * move artifact to target directory, return the moved artifact file path
 *
 * @param targetDirectory
 * @param artifact
 *
 * @return
 */
private Path moveToTargetDir(Path targetDirectory, Artifact artifact) {
    final File artifactFile = artifact.getFile();
    final String artifactFileName = artifactFile.getName();
    final Path targetFile = targetDirectory.resolve(artifactFileName);
    log.debug("copy {} to {}", artifactFileName, targetFile);
    if (!targetDirectory.toFile().exists()) {
        targetDirectory.toFile().mkdirs();
    }
    try {
        Files.copy(artifactFile.toPath(), targetFile, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        final String message = String.format(
                "dependency %s:%s:%s resolved but cannot be moved to target dir: %s",
                artifact.getGroupId(),
                artifact.getArtifactId(),
                artifact.getVersion(),
                e.getMessage()
        );
        throw new DependencyResolveException(message, e);
    }
    return targetFile;
}
 
Example 2
Project: KernelHive   File: MainFrameController.java   View Source Code Vote up 6 votes
/**
 * opens new Tab and associates it with the given {@link File}
 *
 * @param f {@link File}
 */
public void openTab(final File f) {
	SourceCodeEditor sourcePanel;
	if (f != null) {
		sourcePanel = new SourceCodeEditor(frame, f.getName());
		sourcePanel.setFile(f);
		sourcePanel.loadContent(f);
		sourcePanel.setSyntaxStyle(SyntaxStyle.resolveSyntaxStyle(f
				.getName().substring(f.getName().indexOf(".") + 1,
				f.getName().length())));
	} else {
		sourcePanel = new SourceCodeEditor(frame, "new" + newFileCounter);
		newFileCounter++;
	}
	addTabToWorkspacePane(sourcePanel);
}
 
Example 3
Project: hadoop   File: FsDatasetUtil.java   View Source Code Vote up 6 votes
/**
 * Find the meta-file for the specified block file
 * and then return the generation stamp from the name of the meta-file.
 */
static long getGenerationStampFromFile(File[] listdir, File blockFile) {
  String blockName = blockFile.getName();
  for (int j = 0; j < listdir.length; j++) {
    String path = listdir[j].getName();
    if (!path.startsWith(blockName)) {
      continue;
    }
    if (blockFile == listdir[j]) {
      continue;
    }
    return Block.getGenerationStamp(listdir[j].getName());
  }
  FsDatasetImpl.LOG.warn("Block " + blockFile + " does not have a metafile!");
  return GenerationStamp.GRANDFATHER_GENERATION_STAMP;
}
 
Example 4
Project: incubator-netbeans   File: FilesystemInterceptorTest.java   View Source Code Vote up 6 votes
public void testRenameUnversionedFolder_FO() throws Exception {
    // init
    File fromFolder = new File(repositoryLocation, "fromFolder");
    fromFolder.mkdirs();
    File fromFile = new File(fromFolder, "file");
    fromFile.createNewFile();
    File toFolder = new File(repositoryLocation, "toFolder");
    File toFile = new File(toFolder, fromFile.getName());

    // rename
    h.setFilesToRefresh(new HashSet<File>(Arrays.asList(fromFolder, toFolder)));
    renameFO(fromFolder, toFolder);
    assertTrue(h.waitForFilesToRefresh());

    // test
    assertFalse(fromFolder.exists());
    assertTrue(toFolder.exists());

    assertEquals(EnumSet.of(Status.UPTODATE), getCache().getStatus(fromFile).getStatus());
    assertEquals(EnumSet.of(Status.NEW_INDEX_WORKING_TREE, Status.NEW_HEAD_WORKING_TREE), getCache().getStatus(toFile).getStatus());
}
 
Example 5
Project: OpenHomeAnalysis   File: OhaHelper.java   View Source Code Vote up 6 votes
/**
 * Compactar uma arquivo.
 * @param inputFile informar o arquivo a ser compactado.
 * @param zipFilePath informar o nome e caminho zip.
 * @param iZipFile se necessário, informar uma {@link IZipFile}.
 * @throws IOException
 */
public static void zipFile(File inputFile, String zipFilePath, IZipFile iZipFile) throws IOException {
    FileOutputStream fileOutputStream = new FileOutputStream(zipFilePath);
    ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
    ZipEntry zipEntry = new ZipEntry(inputFile.getName());
    zipOutputStream.putNextEntry(zipEntry);
    FileInputStream fileInputStream = new FileInputStream(inputFile);
    FileChannel fileChannel = fileInputStream.getChannel();
    FileLock fileLock = fileChannel.tryLock(0L, Long.MAX_VALUE, /*shared*/true);
    long sizeToZip = fileInputStream.available();
    long sizeCompacted = 0;
    try {
        byte[] buf = new byte[1024];
        int bytesRead;
        while ((bytesRead = fileInputStream.read(buf)) > 0) {
            sizeCompacted += bytesRead;
            zipOutputStream.write(buf, 0, bytesRead);
            if (iZipFile != null) iZipFile.progress(sizeToZip, sizeCompacted);
        }
    } finally {
        fileLock.release();
        zipOutputStream.closeEntry();
        zipOutputStream.close();
        fileOutputStream.close();
    }
}
 
Example 6
Project: chordatlas   File: AlignStandalone2d.java   View Source Code Vote up 5 votes
@Override
public int compare( File o1, File o2 ) {
	
	String 
			a = o1.getName(), 
			b = o2.getName();
	
	try {
		return Integer.compare( Integer.parseInt(a), Integer.parseInt( b ) );
	}
	catch (Throwable th) {
		return a.compareTo( b );
	}
}
 
Example 7
Project: incubator-netbeans   File: Workspace.java   View Source Code Vote up 5 votes
public Variable(String name, String location) {
    this.name = name;
    this.location = location;
    File f = new File(location);
    fileVar = f.exists() && f.isFile();
    if (fileVar) {
        file = f.getName();
        this.location = f.getParentFile().getAbsolutePath();
    }
}
 
Example 8
Project: vexillo   File: VexMoji.java   View Source Code Vote up 5 votes
private static void process(Options o) {
	FlagFontFamily font = new FlagFontFamily(o.encoding);
	font.name = o.name;
	font.copyright = o.copyright;
	font.vendorId = o.vendorId;
	font.emAscent = o.emAscent;
	font.emDescent = o.emDescent;
	font.lineAscent = o.lineAscent;
	font.lineDescent = o.lineDescent;
	font.spaceWidth = o.spaceWidth;
	font.leftBearing = o.leftBearing;
	font.rightBearing = o.rightBearing;
	font.glyphBottom = o.glyphBottom;
	font.glyphHeight = o.glyphHeight;
	font.glyphWidth = o.glyphWidth;
	font.bitmapHeight = o.bitmapHeight;
	font.bitmapWidth = o.bitmapWidth;
	font.bitmapGlaze = o.bitmapGlaze;
	for (File flagFile : o.flagFiles) {
		Flag flag = readFlag(flagFile);
		if (flag == null) continue;
		String id = flag.getId();
		if (id == null || id.length() == 0) {
			id = flagFile.getName();
			int i = id.lastIndexOf('.');
			if (i > 0) id = id.substring(0, i);
		}
		boolean added = font.addFlag(id, flag, flagFile);
		if (!added) System.err.println("Warning: No encoding for " + flagFile.getName());
	}
	writeFont(o.outputFile, font);
}
 
Example 9
Project: ConcealSharedPreference-Android   File: FileUtils.java   View Source Code Vote up 5 votes
static File moveFile(File file, File dir){
    if (dir == null || file == null)
        return null;

    if (!dir.exists()) {
        if (dir.mkdirs()) {
            File newFile = new File(dir, file.getName());
            FileChannel outputChannel;
            FileChannel inputChannel;
            try {
                outputChannel = new FileOutputStream(newFile).getChannel();
                inputChannel = new FileInputStream(file).getChannel();
                inputChannel.transferTo(0, inputChannel.size(), outputChannel);
                inputChannel.close();

                inputChannel.close();
                outputChannel.close();

                file.delete();
            }
            catch (Exception e){
                return null;
            }

            return newFile;
        }
    }

    return file;
}
 
Example 10
Project: csap-core   File: Application.java   View Source Code Vote up 5 votes
public String getRootModelBuildLocation () {
	if ( getSourceLocation()
		.startsWith( "http" ) ) {
		File f = new File( getSourceLocation()
			.substring( getSourceLocation()
				.indexOf( "/" ) ) );
		return STAGING + "/build/" + f.getName();
	} else {
		return STAGING + "/build" + getSourceLocation();
	}

}
 
Example 11
Project: EatDubbo   File: ChartsPageHandler.java   View Source Code Vote up 5 votes
public Page handle(URL url) {
    String service = url.getParameter("service");
    if (service == null || service.length() == 0) {
        throw new IllegalArgumentException("Please input service parameter.");
    }
    String date = url.getParameter("date");
    if (date == null || date.length() == 0) {
        date = new SimpleDateFormat("yyyyMMdd").format(new Date());
    }
    List<List<String>> rows = new ArrayList<List<String>>();
    String directory = SimpleMonitorService.getInstance().getChartsDirectory();
    File chartsDir = new File(directory);
    String filename = directory + "/" + date + "/" + service;
    File serviceDir = new File(filename);
    if (serviceDir.exists()) {
        File[] methodDirs = serviceDir.listFiles();
        for (File methodDir : methodDirs) {
            String methodUri = chartsDir.getName() + "/" + date + "/" + service + "/" + methodDir.getName() + "/";
            rows.add(toRow(methodDir, methodUri));
        }
    }
    StringBuilder nav = new StringBuilder();
    nav.append("<a href=\"services.html\">Services</a> &gt; ");
    nav.append(service);
    nav.append(" &gt; <a href=\"providers.html?service=");
    nav.append(service);
    nav.append("\">Providers</a> | <a href=\"consumers.html?service=");
    nav.append(service);
    nav.append("\">Consumers</a> | <a href=\"statistics.html?service=");
    nav.append(service);
    nav.append("&date=");
    nav.append(date);
    nav.append("\">Statistics</a> | Charts &gt; <input type=\"text\" style=\"width: 65px;\" name=\"date\" value=\"");
    nav.append(date);
    nav.append("\" onkeyup=\"if (event.keyCode == 10 || event.keyCode == 13) {window.location.href='charts.html?service=");
    nav.append(service);
    nav.append("&date=' + this.value;}\" />");
    return new Page(nav.toString(), "Charts (" + rows.size() + ")",
            new String[] { "Method", "Requests per second (QPS)", "Average response time (ms)"}, rows);
}
 
Example 12
Project: recipe-interpretation   File: RecipeSentenceSegmenter.java   View Source Code Vote up 5 votes
public void createStepFiles(String dir) {
	File directory = new File(dir);
	File[] filelist = directory.listFiles();
	for (File file : filelist) {
		if (file.getName().endsWith(".txt")) {
			try {
				BufferedReader br = new BufferedReader(new FileReader(file));
				String line;
				List<String> steps = new ArrayList<String>();
				boolean in_steps = false;
				while ((line = br.readLine()) != null) {
					if (line.trim().length() == 0) {
						continue;
					} else if (line.trim().equals("Steps")) {
						in_steps = true;
					} else if (line.trim().equals("Ingredients")) {
						break;
					} else if (line.trim().startsWith("Data Parsed")) {
						break;
					} else if (in_steps) {
						steps.add(line.trim());
					}
				}
				br.close();

				BufferedWriter bw = new BufferedWriter(new FileWriter("/Users/chloe/Research/recipes/AllRecipesSteps/" + file.getName()));
				for (String step : steps) {
					List<String> sentences = Utils.splitStepSentences(step);
					for (String sentence : sentences) {
						bw.write(sentence + "\n");
					}
				}
				bw.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}
}
 
Example 13
Project: AgentWorkbench   File: ArchiveFileHandler.java   View Source Code Vote up 5 votes
/**
 * Determines the archive format of the given file based on its suffix.
 *
 * @param archiveFile the archive file
 * @return the archive format, null if not recognized or not supported
 */
private ArchiveFormat determineArchiveFormat(File archiveFile) {
	String fileName = archiveFile.getName();
	String suffix = fileName.substring(fileName.indexOf('.') + 1);
	if (fileName.endsWith("zip") || suffix.endsWith("agui")) {
		return ArchiveFormat.ZIP;
	} else if (suffix.endsWith("tar.gz")) {
		return ArchiveFormat.TAR_GZ;
	} else {
		return null;
	}
}
 
Example 14
Project: incubator-netbeans   File: FilesystemInterceptorTest.java   View Source Code Vote up 5 votes
public void testMoveA2B_CreateA_FO() throws Exception {
    // init
    File fileA = new File(repositoryLocation, "file");
    fileA.createNewFile();
    File folderB = new File(repositoryLocation, "folderB");
    folderB.mkdirs();
    add();
    commit();

    File fileB = new File(folderB, fileA.getName());

    // move
    h.setFilesToRefresh(new HashSet<File>(Arrays.asList(fileA, fileB)));
    moveFO(fileA, fileB);
    assertTrue(h.waitForFilesToRefresh());

    // create from file
    h.setFilesToRefresh(new HashSet<File>(Arrays.asList(fileA)));
    FileUtil.toFileObject(fileA.getParentFile()).createData(fileA.getName());
    assertTrue(h.waitForFilesToRefresh());

    // test
    assertTrue(fileB.exists());
    assertTrue(fileA.exists());

    //should be uptodate
    assertEquals(EnumSet.of(Status.UPTODATE), getCache().getStatus(fileA).getStatus());
    FileInformation info = getCache().getStatus(fileB);
    assertEquals(EnumSet.of(Status.NEW_HEAD_INDEX, Status.NEW_HEAD_WORKING_TREE), info.getStatus());
    assertEquals(fileA, info.getOldFile());
    assertTrue(info.isRenamed());
}
 
Example 15
Project: Reer   File: Signature.java   View Source Code Vote up 4 votes
@Nullable
private String fileName() {
    final File file = getFile();
    return file != null ? file.getName() : null;
}
 
Example 16
Project: BaseClient   File: Shaders.java   View Source Code Vote up 4 votes
static ArrayList listOfShaders()
{
    ArrayList<String> arraylist = new ArrayList();
    arraylist.add(packNameNone);
    arraylist.add(packNameDefault);

    try
    {
        if (!shaderpacksdir.exists())
        {
            shaderpacksdir.mkdir();
        }

        File[] afile = shaderpacksdir.listFiles();

        for (int i = 0; i < afile.length; ++i)
        {
            File file1 = afile[i];
            String s = file1.getName();

            if (file1.isDirectory())
            {
                File file2 = new File(file1, "shaders");

                if (file2.exists() && file2.isDirectory())
                {
                    arraylist.add(s);
                }
            }
            else if (file1.isFile() && s.toLowerCase().endsWith(".zip"))
            {
                arraylist.add(s);
            }
        }
    }
    catch (Exception var6)
    {
        ;
    }

    return arraylist;
}
 
Example 17
Project: mylion-mvn   File: StringTools.java   View Source Code Vote up 4 votes
public static String getFileName(String className){
	File f = new File(className);
	className = f.getName() ;
	
	return className; 
}
 
Example 18
Project: javaide   File: LocalSdk.java   View Source Code Vote up 4 votes
private void scanExtras(File collectionDir, Collection<LocalPkgInfo> outCollection) {
    for (File vendorDir : mFileOp.listFiles(collectionDir)) {
        if (!shouldVisitDir(PkgType.PKG_EXTRA, vendorDir)) {
            continue;
        }

        for (File extraDir : mFileOp.listFiles(vendorDir)) {
            if (!shouldVisitDir(PkgType.PKG_EXTRA, extraDir)) {
                continue;
            }

            Properties props = parseProperties(new File(extraDir, SdkConstants.FN_SOURCE_PROP));
            NoPreviewRevision rev =
                PackageParserUtils.getPropertyNoPreview(props, PkgProps.PKG_REVISION);
            if (rev == null) {
                continue; // skip, no revision
            }

            String oldPaths =
                PackageParserUtils.getProperty(props, PkgProps.EXTRA_OLD_PATHS, null);

            String vendorId   = vendorDir.getName();
            String vendorDisp = props.getProperty(PkgProps.EXTRA_VENDOR_DISPLAY);
            if (vendorDisp == null || vendorDisp.isEmpty()) {
                vendorDisp = vendorId;
            }

            String displayName = props.getProperty(PkgProps.EXTRA_NAME_DISPLAY, null);

            LocalExtraPkgInfo pkgInfo = new LocalExtraPkgInfo(
                    this,
                    extraDir,
                    props,
                    new IdDisplay(vendorId, vendorDisp),
                    extraDir.getName(),
                    displayName,
                    PkgDescExtra.convertOldPaths(oldPaths),
                    rev);
            outCollection.add(pkgInfo);
        }
    }
}
 
Example 19
Project: BaseClient   File: ConnectedTextures.java   View Source Code Vote up 4 votes
private static String[] collectFilesFolder(File p_collectFilesFolder_0_, String p_collectFilesFolder_1_, String p_collectFilesFolder_2_, String p_collectFilesFolder_3_)
{
    List list = new ArrayList();
    String s = "assets/minecraft/";
    File[] afile = p_collectFilesFolder_0_.listFiles();

    if (afile == null)
    {
        return new String[0];
    }
    else
    {
        for (int i = 0; i < afile.length; ++i)
        {
            File file1 = afile[i];

            if (file1.isFile())
            {
                String s3 = p_collectFilesFolder_1_ + file1.getName();

                if (s3.startsWith(s))
                {
                    s3 = s3.substring(s.length());

                    if (s3.startsWith(p_collectFilesFolder_2_) && s3.endsWith(p_collectFilesFolder_3_))
                    {
                        list.add(s3);
                    }
                }
            }
            else if (file1.isDirectory())
            {
                String s1 = p_collectFilesFolder_1_ + file1.getName() + "/";
                String[] astring = collectFilesFolder(file1, s1, p_collectFilesFolder_2_, p_collectFilesFolder_3_);

                for (int j = 0; j < astring.length; ++j)
                {
                    String s2 = astring[j];
                    list.add(s2);
                }
            }
        }

        String[] astring1 = (String[])((String[])list.toArray(new String[list.size()]));
        return astring1;
    }
}
 
Example 20
Project: s-store   File: TestSStoreLogicalRecovery.java   View Source Code Vote up 4 votes
File scanForLatestLogFile(File logDir, String prefix){
    System.err.println("Scanning logDir :" + logDir.getAbsolutePath());           

    final String logPrefix = prefix;
    FilenameFilter cleaner = new FilenameFilter() {
        public boolean accept(File dir, String file) {
            return  file.startsWith(logPrefix) && file.endsWith(CommandLogWriter.LOG_OUTPUT_EXT);
        }
    };

    File[] logFiles = logDir.listFiles(cleaner);
    File latestFile = null, prevFile = null;        
    //long maxTimeStamp = Long.MIN_VALUE;
    String maxTimeStamp = "0";
    
    for (File logFile : logFiles) {
        String name = logFile.getName();
        String delims = "_|\\.";
        String[] tokens = name.split(delims);

        //System.err.println("Tokens :"+Arrays.toString(tokens));

        if(tokens.length <= 1)
            continue;
        
        //long fileTimestamp = Long.parseLong(tokens[1]) ;
        String fileTimestamp = (tokens[1]) ;
        if(fileTimestamp.compareTo(maxTimeStamp) > 0){
            maxTimeStamp = fileTimestamp;
            prevFile = latestFile;
            latestFile = logFile;         
        }
        else
        {
            prevFile = logFile;
        }
    }       

    if(prevFile != null){
        System.err.println("Using logfile :" + prevFile.getAbsolutePath());           
    }

    if(latestFile != null){
        System.err.println("Found latest logfile :" + latestFile.getAbsolutePath());           
    }
    
    return prevFile;
}