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

The following are Jave code examples for showing how to use getPath() 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: simple-share-android   File: FileUtils.java   View Source Code Vote up 6 votes
private static void compressFile(String currentDir, ZipOutputStream zout, File[] files) throws Exception {
    byte[] buffer = new byte[1024];
    for (File fi : files) {
        if (fi.isDirectory()) {
            compressFile(currentDir + "/" + fi.getName(), zout, fi.listFiles());
            continue;
        }
        ZipEntry ze = new ZipEntry(currentDir + "/" + fi.getName());
        FileInputStream fin = new FileInputStream(fi.getPath());
        zout.putNextEntry(ze);
        int length;
        while ((length = fin.read(buffer)) > 0) {
            zout.write(buffer, 0, length);
        }
        zout.closeEntry();
        fin.close();
    }
}
 
Example 2
Project: r8   File: MultiDexExtractor.java   View Source Code Vote up 6 votes
/**
 * This removes any files that do not have the correct prefix.
 */
private static void prepareDexDir(File dexDir, final String extractedFilePrefix)
        throws IOException {
    dexDir.mkdir();
    if (!dexDir.isDirectory()) {
        throw new IOException("Failed to create dex directory " + dexDir.getPath());
    }

    // Clean possible old files
    FileFilter filter = new FileFilter() {

        @Override
        public boolean accept(File pathname) {
            return !pathname.getName().startsWith(extractedFilePrefix);
        }
    };
    File[] files = dexDir.listFiles(filter);
    if (files == null) {
        return;
    }
    for (File oldFile : files) {
        if (!oldFile.delete()) {
        } else {
        }
    }
}
 
Example 3
Project: parabuild-ci   File: FileUtil.java   View Source Code Vote up 6 votes
public void makeParentDirectories(File f) {

        String parent = f.getParent();

        if (parent != null) {
            new File(parent).mkdirs();
        } else {

            // workaround for jdk 1.1 bug (returns null when there is a parent)
            parent = f.getPath();

            int index = parent.lastIndexOf('/');

            if (index > 0) {
                parent = parent.substring(0, index);

                new File(parent).mkdirs();
            }
        }
    }
 
Example 4
Project: javaide   File: FileManager.java   View Source Code Vote up 6 votes
public static ArrayList<String> listClassName(File src) {
    if (!src.exists()) return new ArrayList<>();

    String[] exts = new String[]{"java"};
    Collection<File> files = FileUtils.listFiles(src, exts, true);

    ArrayList<String> classes = new ArrayList<>();
    String srcPath = src.getPath();
    for (File file : files) {
        String javaPath = file.getPath();
        javaPath = javaPath.substring(srcPath.length() + 1, javaPath.length() - 5); //.java
        javaPath = javaPath.replace(File.separator, ".");
        classes.add(javaPath);
    }
    return classes;
}
 
Example 5
Project: javaide   File: FileWordReader.java   View Source Code Vote up 5 votes
/**
 * Creates a new FileWordReader for the given file.
 */
public FileWordReader(File file) throws IOException
{
    super(file.getParentFile());

    this.name   = file.getPath();
    this.reader = new LineNumberReader(
                  new BufferedReader(
                  new FileReader(file)));
}
 
Example 6
Project: aos-FileCoreLibrary   File: FileManagerCore.java   View Source Code Vote up 5 votes
private boolean deleteFile(File file){
    ContentResolver cr = context.getContentResolver();
    Uri uri = MediaStore.Files.getContentUri("external");
    String where = MediaColumns.DATA + "=?";
    String[] selectionArgs = { file.getPath() };
    boolean ret = cr.delete(uri, where, selectionArgs) > 0;
    ret |= file.delete();
    return ret;
}
 
Example 7
Project: ViewDebugHelper   File: SdCardUtils.java   View Source Code Vote up 5 votes
/**
 * 获得SD卡总大小
 * 
 * @return
 */
public static long getSDTotalSize() {
	File path = Environment.getExternalStorageDirectory();
	StatFs stat = new StatFs(path.getPath());
	long blockSize = stat.getBlockSize();
	long totalBlocks = stat.getBlockCount();
	return blockSize * totalBlocks;
}
 
Example 8
Project: bcg   File: ClientModule.java   View Source Code Vote up 5 votes
@Provides
@Singleton
public Cache provideCache(@Named("cacheDir") File cacheDir, @Named("cacheSize") long cacheSize) {
    Cache cache = null;

    try {
        cache = new Cache(new File(cacheDir.getPath(), HTTP_CACHE_PATH), cacheSize);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return cache;
}
 
Example 9
Project: react-native-udesk   File: UdeskUtil.java   View Source Code Vote up 5 votes
public static boolean audiofileIsDown(Context context, String url) {
    if (TextUtils.isEmpty(url)) {
        return false;
    }
    String fileName = url.substring(url.lastIndexOf("/") + 1);
    File mediaStorageDir = new File(
            context.getExternalFilesDir(Environment.DIRECTORY_RINGTONES),
            AudioFolderName);
    if (!mediaStorageDir.exists()) {
        return false;
    }
    String filepath = mediaStorageDir.getPath() + File.separator + fileName;
    File file = new File(filepath);
    return file.exists();
}
 
Example 10
Project: AndroidBasicLibs   File: MemoryCache.java   View Source Code Vote up 5 votes
/**
 * Get available internal memory size
 *
 * @return
 */
public static long getAvailableInternalMemorySize() {
    File path = Environment.getDataDirectory();
    StatFs stat = new StatFs(path.getPath());
    long blockSize = stat.getBlockSize();
    long availableBlocks = stat.getAvailableBlocks();
    return availableBlocks * blockSize;
}
 
Example 11
Project: Yass   File: YassSelectSongScreen.java   View Source Code Vote up 5 votes
/**
 * Description of the Method
 */
public void playSelectedSong() {
    getTheme().unloadSample("file:" + currentSong);

    if (selectedItem < itemCount - 1) {
        YassScreenGroup group = getGroupAt(getSelectedGroup());
        YassSongData sd = getSongDataAt(group.getSongAt(selectedItem));
        File f = sd.getAudio();

        int startMillis = sd.getPreviewStart();
        if (startMillis <= 0) {
            startMillis = sd.getMedleyStart();
        }
        if (startMillis <= 0) {
            startMillis = sd.getStart();
        }
        if (startMillis <= 0) {
            startMillis = sd.getGap();
        }
        if (startMillis <= 0) {
            startMillis = 0;
        }

        currentSong = f.getPath();

        if (playbackThread != null) {
            playbackThread.interrupt = true;
        }
        playbackThread = new PlaybackThread(currentSong, startMillis);
        playbackThread.start();
    }
}
 
Example 12
Project: AndroidBasicLibs   File: MemoryUtil.java   View Source Code Vote up 5 votes
/**
 * Get available external memory size
 *
 * @return
 */
public static long getAvailableExternalMemorySize() {
    if (isExternalMemoryAvailable()) {
        File path = Environment.getExternalStorageDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return availableBlocks * blockSize;
    } else {
        return ERROR;
    }
}
 
Example 13
Project: jdk8u-jdk   File: ProcessImpl.java   View Source Code Vote up 5 votes
private static String getExecutablePath(String path)
    throws IOException
{
    boolean pathIsQuoted = isQuoted(true, path,
            "Executable name has embedded quote, split the arguments");

    // Win32 CreateProcess requires path to be normalized
    File fileToRun = new File(pathIsQuoted
        ? path.substring(1, path.length() - 1)
        : path);

    // From the [CreateProcess] function documentation:
    //
    // "If the file name does not contain an extension, .exe is appended.
    // Therefore, if the file name extension is .com, this parameter
    // must include the .com extension. If the file name ends in
    // a period (.) with no extension, or if the file name contains a path,
    // .exe is not appended."
    //
    // "If the file name !does not contain a directory path!,
    // the system searches for the executable file in the following
    // sequence:..."
    //
    // In practice ANY non-existent path is extended by [.exe] extension
    // in the [CreateProcess] funcion with the only exception:
    // the path ends by (.)

    return fileToRun.getPath();
}
 
Example 14
Project: jermit   File: Xmodem1.java   View Source Code Vote up 5 votes
/**
 * Run the test.
 */
@Override
public void doTest() throws IOException, TestFailedException {
    System.out.printf("Xmodem1: basic ASCII file download\n");

    // Process:
    //
    //   1. Extract jermit/tests/data/ALICE26A_NO_EOT.TXT to
    //      a temp file.
    //   2. Spawn 'sx /path/to/ALICE26A_NO_EOT.TXT'
    //   3. Spin up XmodemReceiver to download to a temp file.
    //   4. Read both files and compare contents.

    File source = File.createTempFile("send-xmodem", ".txt");
    saveResourceToFile("jermit/tests/data/ALICE26A_NO_EOT.TXT", source);
    source.deleteOnExit();

    File destination = File.createTempFile("receive-xmodem", ".txt");
    destination.deleteOnExit();

    ProcessBuilder sxb = new ProcessBuilder("sx", source.getPath());
    Process sx = sxb.start();

    // Allow overwrite of destination file, because we just created it.
    XmodemReceiver rx = new XmodemReceiver(XmodemSession.Flavor.VANILLA,
        sx.getInputStream(), sx.getOutputStream(),
        destination.getPath(), true);

    rx.run();
    if (!compareFiles(source, destination)) {
        throw new TestFailedException("Files are not the same");
    }

}
 
Example 15
Project: XModulable   File: ClassUtils.java   View Source Code Vote up 5 votes
/**
     * get all the dex path
     *
     * @param context the application context
     * @return all the dex path
     * @throws PackageManager.NameNotFoundException
     * @throws IOException
     */
    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);

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

        //the prefix of extracted file, ie: test.classes
        String extractedFilePrefix = sourceApk.getName() + EXTRACTED_NAME_EXT;

//        如果VM已经支持了MultiDex,就不要去Secondary Folder加载 Classesx.zip了,那里已经么有了
//        通过是否存在sp中的multidex.version是不准确的,因为从低版本升级上来的用户,是包含这个sp配置的
        if (!isVMMultidexCapable()) {
            //the total dex numbers
            int totalDexNumber = getMultiDexPreferences(context).getInt(KEY_DEX_NUMBER, 1);
            File dexDir = new File(applicationInfo.dataDir, SECONDARY_FOLDER_NAME);

            for (int secondaryNumber = 2; secondaryNumber <= totalDexNumber; secondaryNumber++) {
                //for each dex file, ie: test.classes2.zip, test.classes3.zip...
                String fileName = extractedFilePrefix + secondaryNumber + EXTRACTED_SUFFIX;
                File extractedFile = new File(dexDir, fileName);
                if (extractedFile.isFile()) {
                    sourcePaths.add(extractedFile.getAbsolutePath());
                    //we ignore the verify zip part
                } else {
                    throw new IOException("Missing extracted secondary dex file '" + extractedFile.getPath() + "'");
                }
            }
        }

        if (XModulable.debuggable()) { // Search instant run support only debuggable
            sourcePaths.addAll(tryLoadInstantRunDexFile(applicationInfo));
        }
        return sourcePaths;
    }
 
Example 16
Project: BEAST   File: WindowsOStoolbox.java   View Source Code Vote up 5 votes
/**
 * 
 * @return the String that should lead to a vsDevCMD which is required to
 *         run cbmc on windows
 * @throws IOException in case the VScmd couldn't be found this gets thrown
 */
public static String getVScmdPath() throws IOException {

    File file = new File(SuperFolderFinder.getSuperFolder() + RELATIVEPATHTOVSCMD);

    if (Files.isExecutable(file.toPath())) {
        return file.getPath();
    } else { // we were unable to locate the command promp in the resources
        // and search now for it in the common install directories

        Path x86 = new File("C:/Program Files (x86)").toPath();
        Path x64 = new File("C:/Program Files").toPath();
        String searchTerm = "Microsoft Visual Studio";
        String pathToBatch = "/Common7/Tools/VsDevCmd.bat";

        ArrayList<String> toSearch = new ArrayList<>();
        Files.list(x86).filter(Files::isReadable).filter(path -> path.toString().contains(searchTerm))
                .forEach(VSPath -> toSearch.add(VSPath.toString()));
        Files.list(x64).filter(Files::isReadable).filter(path -> path.toString().contains(searchTerm))
                .forEach(VSPath -> toSearch.add(VSPath.toString()));

        for (Iterator<String> iterator = toSearch.iterator(); iterator.hasNext();) {
            String toCheck = ((String) iterator.next()) + pathToBatch;

            if (Files.isReadable(new File(toCheck).toPath())) {
                return toCheck;
            }
        }

        ErrorForUserDisplayer.displayError("The progam was unable to find a Developer Command Prompt for Visual Studio. \n"
                + " Please install it if you haven't and search for the vsCMD.bat in it! \n"
                + " Please copy the .bat to the folder /windows/ in your BEST install directory"
                + "(named \"VsDevCmd.bat\") so it can be found automatically.");

        return "The progam was unable to find a Developer Command Prompt for Visual Studio. Look at the error log";
    }
}
 
Example 17
Project: stynico   File: Util.java   View Source Code Vote up 4 votes
public static SDCardInfo getSDCardInfo()
 {
String sDcString = android.os.Environment.getExternalStorageState();

if (sDcString.equals(android.os.Environment.MEDIA_MOUNTED))
{
  File pathFile = android.os.Environment.getExternalStorageDirectory();

  try
  {
	android.os.StatFs statfs = new android.os.StatFs(pathFile.getPath());

	// 获取SDCard上BLOCK总数
	long nTotalBlocks = statfs.getBlockCount();

	// 获取SDCard上每个block的SIZE
	long nBlocSize = statfs.getBlockSize();

	// 获取可供程序使用的Block的数量
	long nAvailaBlock = statfs.getAvailableBlocks();

	// 获取剩下的所有Block的数量(包括预留的一般程序无法使用的块)
	long nFreeBlock = statfs.getFreeBlocks();

	SDCardInfo info = new SDCardInfo();
	// 计算SDCard 总容量大小MB
	info.total = nTotalBlocks * nBlocSize;

	// 计算 SDCard 剩余大小MB
	info.free = nAvailaBlock * nBlocSize;

	return info;
  }
  catch (IllegalArgumentException e)
  {
	Log.e(LOG_TAG, e.toString());
  }
}

return null;
 }
 
Example 18
Project: litiengine   File: EditorScreen.java   View Source Code Vote up 4 votes
public void load(File gameFile) {
  final long current = System.nanoTime();
  Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_LOAD, 0, 0);
  Game.getScreenManager().getRenderComponent().setCursorOffsetX(0);
  Game.getScreenManager().getRenderComponent().setCursorOffsetY(0);

  try {
    if (!FileUtilities.getExtension(gameFile).equals(GameFile.FILE_EXTENSION)) {
      log.log(Level.SEVERE, "unsupported file format '" + FileUtilities.getExtension(gameFile) + "'");
      return;
    }

    if (!gameFile.exists()) {
      log.log(Level.SEVERE, "gameFile '" + gameFile + "' doesn't exist");
      return;
    }

    // set up project settings
    this.currentResourceFile = gameFile.getPath();
    this.gameFile = GameFile.load(gameFile.getPath());
    Program.userPreferences.setLastGameFile(gameFile.getPath());
    Program.userPreferences.addOpenedFile(this.currentResourceFile);
    Program.loadRecentFiles();
    this.setProjectPath(FileUtilities.getParentDirPath(gameFile.getAbsolutePath()));

    // load maps from game file
    this.mapComponent.loadMaps(this.getGameFile().getMaps());

    // load sprite sheets from different sources:
    // 1. add sprite sheets from game file
    // 2. add sprite sheets by tile sets of all maps in the game file
    this.loadSpriteSheets(this.getGameFile().getSpriteSheets());

    log.log(Level.INFO, this.getGameFile().getSpriteSheets().size() + " tilesheets loaded from '" + this.currentResourceFile + "'");

    for (Map map : this.mapComponent.getMaps()) {
      this.loadSpriteSheets(map);
    }

    // load custom emitter files
    this.loadCustomEmitters(this.getProjectPath());

    // display first available map after loading all stuff
    // also switch to map component
    if (!this.mapComponent.getMaps().isEmpty()) {
      this.mapComponent.loadEnvironment(this.mapComponent.getMaps().get(0));

      this.changeComponent(ComponentType.MAP);
    }
  } finally {
    Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR, 0, 0);
    log.log(Level.INFO, "Loading gamefile {0} took: {1} ms", new Object[] { gameFile, (System.nanoTime() - current) / 1000000.0 });
    this.setCurrentStatus("gamefile loaded");
  }
}
 
Example 19
Project: s-store   File: TestVoltCompiler.java   View Source Code Vote up 4 votes
public void testUniqueProcedureStatementIds() {
    final File schemaFile = VoltProjectBuilder.writeStringToTempFile("create table T(ID INTEGER);");
    int expected = 5;
    String simpleXML =
        "<?xml version=\"1.0\"?>\n" +
        "<project>" +
        "<database name='database'>" +
        "<schemas>" +
        "<schema path='" + schemaFile.getAbsolutePath() + "'/>" +
        "</schemas>" +
        "<procedures>";
    for (int i = 0; i < expected; i++) {
        simpleXML += "<procedure class='proc" + i + "'><sql>select * from T</sql></procedure>";
    }
    simpleXML += "</procedures>" +
                 "</database>" +
                 "</project>";

    final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleXML);
    final String projectPath = projectFile.getPath();

    final VoltCompiler compiler = new VoltCompiler();
    final Catalog catalog = compiler.compileCatalog(projectPath, cluster_config);
    assertNotNull(catalog);
    
    Set<Integer> proc_ids = new HashSet<Integer>();
    Set<Integer> stmt_ids = new HashSet<Integer>();
    
    Database catalog_db = CatalogUtil.getDatabase(catalog);
    int actual_procs = 0;
    int actual_stmts = 0;
    for (Procedure catalog_proc : catalog_db.getProcedures()) {
        assertFalse(proc_ids.contains(catalog_proc.getId()));
        for (Statement catalog_stmt : catalog_proc.getStatements()) {
            assertFalse(stmt_ids.contains(catalog_stmt.getId()));
            stmt_ids.add(catalog_stmt.getId());
            if (catalog_proc.getSystemproc() == false) actual_stmts++;
        } // FOR
        proc_ids.add(catalog_proc.getId());
        if (catalog_proc.getSystemproc() == false) actual_procs++;
    } // FOR
    assertEquals(expected, actual_procs);
    assertEquals(expected, actual_stmts);
}
 
Example 20
Project: alfresco-repository   File: FileExportPackageHandler.java   View Source Code Vote up 3 votes
/**
 * Constuct Handler
 * 
 * @param destDir  destination directory
 * @param dataFile  filename of data file (relative to destDir)
 * @param contentDir  directory for content (relative to destDir)
 * @param overwrite  force overwrite of existing package directory
 * @param mimetypeService (optional) mimetype service
 */
public FileExportPackageHandler(File destDir, File dataFile, File contentDir, boolean overwrite, MimetypeService mimetypeService)
{
    this.contentDir = contentDir;
    this.absContentDir = new File(destDir, contentDir.getPath());
    this.absDataFile = new File(destDir, dataFile.getPath());
    this.overwrite = overwrite;
    this.mimetypeService = mimetypeService;
}