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

The following are Jave code examples for showing how to use getParent() 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: Auto.js-ApkBuilder   File: MainActivity.java   View Source Code Vote up 7 votes
private void build(File tmpDir, File js) throws Exception {
    File outApk = new File(js.getParent(), js.getName() + ".apk");
    InputStream inApk = getAssets().open("template.apk");
    ApkBuilder apkBuilder = new ApkBuilder(inApk, outApk, tmpDir.getPath())
            .prepare();
    apkBuilder.editManifest()
            .setVersionCode(5000)
            .setVersionName("1.2.3")
            .setAppName("Hello")
            .setPackageName("com.stardust.xxx")
            .commit();
    apkBuilder.replaceFile("assets/script.js", js.getPath())
            .setArscPackageName("com.stardust.xxx")
            .build()
            .sign();
}
 
Example 2
Project: BBSSDK-for-Android   File: FileUtils.java   View Source Code Vote up 6 votes
/**
 * 重命名文件
 *
 * @param file    文件
 * @param newName 新名称
 * @return {@code true}: 重命名成功<br>{@code false}: 重命名失败
 */
public static boolean rename(final File file, final String newName) {
	// 文件为空返回false
	if (file == null) {
		return false;
	}
	// 文件不存在返回false
	if (!file.exists()) {
		return false;
	}
	// 新的文件名为空返回false
	if (isSpace(newName)) {
		return false;
	}
	// 如果文件名没有改变返回true
	if (newName.equals(file.getName())) {
		return true;
	}
	File newFile = new File(file.getParent() + File.separator + newName);
	// 如果重命名的文件已存在返回false
	return !newFile.exists()
			&& file.renameTo(newFile);
}
 
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: atlas   File: ZipAlignUtils.java   View Source Code Vote up 6 votes
public static synchronized File doZipAlign(final AndroidBuilder androidBuilder, Project project, final File apkFile) {

        final File zipalignedFile = new File(apkFile.getParent(), apkFile.getName().replace(".apk", "-zipaligned.apk"));

        project.exec(new Action<ExecSpec>() {
            @Override
            public void execute(ExecSpec execSpec) {

                String path = androidBuilder.getTargetInfo()
                        .getBuildTools().getPath(ZIP_ALIGN);
                execSpec.executable(new File(path));
                execSpec.args("-f", "4");
                execSpec.args(apkFile);
                execSpec.args(zipalignedFile);
            }
        });

        return zipalignedFile;
    }
 
Example 5
Project: buildAPKsSamples   File: AbstractPicViewDatabase.java   View Source Code Vote up 6 votes
/**
 * Returns a usable database with the given name. If a database with this name
 * already exists, it is returned. Otherwise created with the given SQL create
 * query.
 */
protected static SQLiteDatabase getUsableDataBase(String dbName,
    String sqlCreateQuery) {
  File dbFile = getPathToDb(dbName);

  File fileDirectory = new File(dbFile.getParent());
  if (!fileDirectory.exists()) {
    // Make sure the path for the file exists, before creating the
    // database.
    fileDirectory.mkdirs();
  }
  Log.d(TAG, "DB Path: " + dbFile.getAbsolutePath());
  boolean initDb = !dbFile.exists();
  try {
    SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(dbFile, null);

    if (initDb) {
      result.execSQL(sqlCreateQuery);
    }

    return result;
  } catch (SQLiteException ex) {
    Log.w(TAG, "Could not open or image database.");
    return null;
  }
}
 
Example 6
Project: sumo   File: SumoSafeReader.java   View Source Code Vote up 6 votes
/**
 * Return the mesaurements
 * 
 * @return
 */
public void readMesasurementFilesFromSafe() {
	XPathExpression<Element> expr = xFactory
			.compile(
					"/xfdu:XFDU/dataObjectSection/dataObject[@repID='s1Level1ProductSchema']/byteStream/fileLocation",
					Filters.element(), null, xfdu);

	List<Element> values = expr.evaluate(safe);
	this.measurements=new File[values.size()];
	
	File safefile = new File(safePath);
	String measurementPath = safefile.getParent() + "/measurement";

	for (int i = 0; i < values.size(); i++) {
		Element e = values.get(i);
		String href = e.getAttributeValue("href");
		if (href.startsWith("./"))
			href = href.substring(2);
		measurements[i] = new File(measurementPath + "/" + href);
		System.out.println(measurements[i]);
	}

}
 
Example 7
Project: datarouter   File: FileTool.java   View Source Code Vote up 5 votes
public static boolean createFileParents(File file){
	if(file.exists()){
		return true;
	}
	File parent = new File(file.getParent());
	if(parent.exists()){
		return true;
	}
	try{
		parent.mkdirs();
	}catch(Exception e){
		return false;
	}
	return true;
}
 
Example 8
Project: openjdk-jdk10   File: Driver.java   View Source Code Vote up 5 votes
protected File compileTestFile(File f, String testClass, String... extraParams) {
    List<String> options = new ArrayList<>();
    options.addAll(Arrays.asList(extraParams));
    options.add(f.getPath());
    int rc = com.sun.tools.javac.Main.compile(options.toArray(new String[options.size()]));
    if (rc != 0)
        throw new Error("compilation failed. rc=" + rc);
    String path = f.getParent() != null ? f.getParent() : "";
    return new File(path, format("%s.class", testClass));
}
 
Example 9
Project: TreebolicPlugins   File: MainActivity.java   View Source Code Vote up 5 votes
@Override
protected void onActivityResult(final int requestCode, final int resultCode, @NonNull final Intent returnIntent)
{
	switch (requestCode)
	{
		case REQUEST_FILE_CODE:
			if (resultCode == AppCompatActivity.RESULT_OK)
			{
				final Uri fileUri = returnIntent.getData();
				if (fileUri == null)
				{
					break;
				}

				Toast.makeText(this, fileUri.toString(), Toast.LENGTH_SHORT).show();
				final File file = new File(fileUri.getPath());
				final String parent = file.getParent();
				final File parentFile = new File(parent);
				final Uri parentUri = Uri.fromFile(parentFile);
				final String query = file.getName();
				String base = parentUri.toString();
				if (base != null && !base.endsWith("/"))
				{
					base += '/';
				}
				Settings.save(this, query, base);

				updateButton();

				// query
				// query();
			}
			break;
		default:
			break;
	}
	super.onActivityResult(requestCode, resultCode, returnIntent);
}
 
Example 10
Project: StructPro   File: Utils.java   View Source Code Vote up 5 votes
/**
 * Write tags to file
 * @param file File to write
 * @param tag NBT tag to write
 * @throws IOException If writing failed
 */
public static void writeTags(File file, NBTTagCompound tag) throws IOException {
    if (file.getParentFile() != null && !file.getParentFile().exists()) {
        if (!file.getParentFile().mkdirs()) {
            throw new IOException("Can't create path: " + file.getParent());
        }
    }
    try (FileOutputStream fos = new FileOutputStream(file)) {
        CompressedStreamTools.writeCompressed(tag, fos);
    }
}
 
Example 11
Project: sumo   File: Radarsat1Image.java   View Source Code Vote up 5 votes
public void setFile(File imageFile) {
    displayName = imageFile.getPath();
    try {
        dat = new RandomAccessFile(imageFile, "r");
        directory = imageFile.getParent();
    } catch (Exception ex) {
        dispose();
        logger.error("Cannot access the file ",ex);
    }
}
 
Example 12
Project: incubator-netbeans   File: NewClustersRebootTest.java   View Source Code Vote up 5 votes
private void invokeNbExecAndCreateCluster(File workDir, StringBuffer sb, String... args) throws Exception {
        URL u = Lookup.class.getProtectionDomain().getCodeSource().getLocation();
        File f = Utilities.toFile(u.toURI());
        assertTrue("file found: " + f, f.exists());
        File nbexec = org.openide.util.Utilities.isWindows() ? new File(f.getParent(), "nbexec.exe") : new File(f.getParent(), "nbexec");
        assertTrue("nbexec found: " + nbexec, nbexec.exists());
        LOG.log(Level.INFO, "nbexec: {0}", nbexec);

        URL tu = NewClustersRebootCallback.class.getProtectionDomain().getCodeSource().getLocation();
        File testf = Utilities.toFile(tu.toURI());
        assertTrue("file found: " + testf, testf.exists());

        LinkedList<String> allArgs = new LinkedList<String>(Arrays.asList(args));
        allArgs.addFirst("-J-Dnetbeans.mainclass=" + NewClustersRebootCallback.class.getName());
        allArgs.addFirst(System.getProperty("java.home"));
        allArgs.addFirst("--jdkhome");
        allArgs.addFirst(getWorkDirPath());
        allArgs.addFirst("--userdir");
        allArgs.addFirst(testf.getPath());
        allArgs.addFirst("-cp:p");
        allArgs.addFirst("--nosplash");

        if (!org.openide.util.Utilities.isWindows()) {
            allArgs.addFirst(nbexec.getPath());
            allArgs.addFirst("-x");
            allArgs.addFirst("/bin/sh");
        } else {
            allArgs.addFirst(nbexec.getPath());
        }
        LOG.log(Level.INFO, "About to execute {0}@{1}", new Object[]{allArgs, workDir});
        Process p = Runtime.getRuntime().exec(allArgs.toArray(new String[0]), new String[0], workDir);
        LOG.log(Level.INFO, "Process created {0}", p);
        int res = readOutput(sb, p);
        LOG.log(Level.INFO, "Output read: {0}", res);
        String output = sb.toString();
//        System.out.println("nbexec output is: " + output);
        assertEquals("Execution is ok: " + output, 0, res);
    }
 
Example 13
Project: codedemos   File: FileUtil.java   View Source Code Vote up 5 votes
public static boolean rename(File file, String newName) {
    // 文件为空返回false
    if (file == null) return false;
    // 文件不存在返回false
    if (!file.exists()) return false;
    // 新的文件名为空返回false
    if (isSpace(newName)) return false;
    // 如果文件名没有改变返回true
    if (newName.equals(file.getName())) return true;
    File newFile = new File(file.getParent() + File.separator + newName);
    // 如果重命名的文件已存在返回false
    return !newFile.exists()
            && file.renameTo(newFile);
}
 
Example 14
Project: StructPro   File: Utils.java   View Source Code Vote up 5 votes
/**
 * Write tags to file
 * @param file File to write
 * @param tag NBT tag to write
 * @throws IOException If writing failed
 */
public static void writeTags(File file, NBTTagCompound tag) throws IOException {
    if (file.getParentFile() != null && !file.getParentFile().exists()) {
        if (!file.getParentFile().mkdirs()) {
            throw new IOException("Can't create path: " + file.getParent());
        }
    }
    try (FileOutputStream fos = new FileOutputStream(file)) {
        CompressedStreamTools.writeCompressed(tag, fos);
    }
}
 
Example 15
Project: incubator-netbeans   File: NbExecPassesCorrectlyQuotedArgsTest.java   View Source Code Vote up 5 votes
private void run(File workDir, String... args) throws Exception {
    URL u = Lookup.class.getProtectionDomain().getCodeSource().getLocation();
    File f = Utilities.toFile(u.toURI());
    assertTrue("file found: " + f, f.exists());
    File nbexec = Utilities.isWindows() ? new File(f.getParent(), "nbexec.exe") : new File(f.getParent(), "nbexec");
    assertTrue("nbexec found: " + nbexec, nbexec.exists());

    URL tu = MainCallback.class.getProtectionDomain().getCodeSource().getLocation();
    File testf = Utilities.toFile(tu.toURI());
    assertTrue("file found: " + testf, testf.exists());
    
    LinkedList<String> allArgs = new LinkedList<String>(Arrays.asList(args));
    allArgs.addFirst("-J-Dnetbeans.mainclass=" + MainCallback.class.getName());
    allArgs.addFirst(System.getProperty("java.home"));
    allArgs.addFirst("--jdkhome");
    allArgs.addFirst(getWorkDirPath());
    allArgs.addFirst("--userdir");
    allArgs.addFirst(testf.getPath());
    allArgs.addFirst("-cp:p");
    
    if (!Utilities.isWindows()) {
        allArgs.addFirst(nbexec.getPath());
        allArgs.addFirst("-x");
        allArgs.addFirst("/bin/sh");
    } else {
        allArgs.addFirst(nbexec.getPath());
    }
    
    StringBuffer sb = new StringBuffer();
    Process p = Runtime.getRuntime().exec(allArgs.toArray(new String[allArgs.size()]), new String[0], workDir);
    int res = readOutput(sb, p);
    
    String output = sb.toString();
    
    assertEquals("Execution is ok: " + output, 0, res);
}
 
Example 16
Project: loom   File: DirSystemUpdater.java   View Source Code Vote up 5 votes
@Override
protected DirItemAttributes createItemAttributes(final File resource) {
    DirItemAttributes dia = new DirItemAttributes();
    dia.setDirname(resource.getName());
    dia.setItemId(resource.getAbsolutePath());
    dia.setItemName(resource.getName());
    String path = resource.getParent();
    if (path != null) {
        dia.setPath(path);
    }
    dirItems.put(dia.getItemId(), dia);
    return dia;
}
 
Example 17
Project: PACE   File: GenerateEncryptionVersioningFiles.java   View Source Code Vote up 4 votes
/**
 * Generate files for the versioning test.
 *
 * @param config
 *          Configuration file describing how the data is generated.
 * @param destination
 *          Directory data will be placed in.
 * @param entryCount
 *          Number of entries to create in each file.
 * @param entryFieldSize
 *          Size of each field in the generated entries.
 */
private static void generateFiles(File config, File destination, int entryCount, int entryFieldSize) throws Exception {
  String parentDirectory = config.getParent();
  JsonParser parser = new JsonParser();
  JsonObject configJson = parser.parse(new FileReader(config)).getAsJsonObject();

  // Generate the signing keys.
  File keyManifest = Paths.get(parentDirectory, configJson.getAsJsonPrimitive("key-manifest").getAsString()).toFile();
  GenerateKeys.generateKeys(keyManifest, destination, true, false);

  // Generate the data and write it to a file.
  byte[] visibility = new ColumnVisibility(configJson.getAsJsonPrimitive("visibility").getAsString()).getExpression();
  SortedMap<Key,Value> data = GenerateRandomEntries.getRandomData(entryCount, entryFieldSize, visibility);

  LocalFileSystem fs = FileSystem.getLocal(new Configuration());
  RFileWriter writer = RFile.newWriter().to(Paths.get(parentDirectory, configJson.getAsJsonPrimitive("data-table").getAsString()).toString())
      .withFileSystem(fs).build();
  writer.append(data.entrySet());
  writer.close();

  // Generate the files for each configuration.
  for (JsonElement testElem : configJson.getAsJsonArray("tests")) {
    JsonObject test = testElem.getAsJsonObject();
    EncryptionConfig encryptionConfig = new EncryptionConfigBuilder().readFromFile(
        new FileReader(Paths.get(parentDirectory, test.getAsJsonPrimitive("config").getAsString()).toFile())).build();
    EncryptionKeyContainer keyContainer = LocalEncryptionKeyContainer.read(new FileReader(Paths.get(parentDirectory,
        test.getAsJsonPrimitive("keys").getAsString()).toFile()));
    EntryEncryptor encryptor = new EntryEncryptor(encryptionConfig, keyContainer);

    // We have to add entries to a sorted map first, as RFiles must be in order.
    SortedMap<Key,Value> encryptedEntries = new TreeMap<>();
    for (Entry<Key,Value> entry : data.entrySet()) {
      Entry<Key,Value> encryptedEntry = encryptor.encrypt(entry);
      encryptedEntries.put(encryptedEntry.getKey(), encryptedEntry.getValue());
    }

    RFileWriter encryptedWriter = RFile.newWriter().to(Paths.get(parentDirectory, test.getAsJsonPrimitive("table").getAsString()).toString())
        .withFileSystem(fs).build();
    encryptedWriter.append(encryptedEntries.entrySet());
    encryptedWriter.close();
  }
}
 
Example 18
Project: javaide   File: FileExplorerActivity.java   View Source Code Vote up 4 votes
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this, R.layout.file_explorer_activity);

        Intent it = getIntent();
        mode = it.getIntExtra("mode", MODE_PICK_FILE);

        setSupportActionBar(binding.toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle(mode == MODE_PICK_FILE ? R.string.open_file : R.string.save_file);

        lastPath = Pref.getInstance(this).getLastOpenPath();
        if (TextUtils.isEmpty(lastPath)) {
            lastPath = Environment.getExternalStorageDirectory().getPath();
        }

        String destPath = it.getStringExtra("dest_file");

        if (!TextUtils.isEmpty(destPath)) {
            File dest = new File(destPath);
            lastPath = dest.isFile() ? dest.getParent() : dest.getPath();
            binding.filenameEditText.setText(dest.getPath());
        } else {
            binding.filenameEditText.setText("");
        }

        initPager();
        binding.btnSelect.setOnClickListener(this);
        binding.fileEncodingTextView.setOnClickListener(this);

        String encoding = it.getStringExtra("encoding");
        fileEncoding = encoding;
        if (TextUtils.isEmpty(encoding)) {
            encoding = getString(R.string.auto_detection_encoding);
        }
        binding.fileEncodingTextView.setText(encoding);

        binding.filenameLayout.setVisibility(mode == MODE_PICK_FILE ? View.GONE : View.VISIBLE);
//        binding.filenameLayout.setVisibility(View.GONE);
        binding.fileEncodingTextView.setVisibility(View.GONE);

        getFileClipboard().setOnClipboardDataChangedListener(this);
    }
 
Example 19
Project: iTrace-Archive   File: XMLBasicFixationFilter.java   View Source Code Vote up 4 votes
@Override
public void read(File file) throws IOException {
	rawGazes.clear(); //make sure rawGazes is empty
	if (file != null) {
		//Set up needed export data
		fileDir = new String(file.getParent());
		String[] parts = file.getName().split("-");
		devUsername = parts[2];
		sessionID = parts[3] + "-" + parts[4] + "-" + parts[5].split(Pattern.quote("."))[0];
		
		//Read from file
		if(file.getName().lastIndexOf(".") > 0) {
			int i = file.getName().lastIndexOf(".");
			if (file.getName().substring(i+1).equals("xml")) {
				if (file.exists()) {
					try {
						XMLInputFactory factory = XMLInputFactory.newInstance();
						XMLStreamReader reader = factory.createXMLStreamReader(
								new FileReader(file.getAbsolutePath()));
			
						while (reader.hasNext()) {
							int event = reader.next();
							if (event == XMLStreamConstants.START_ELEMENT) {
								if (reader.getLocalName().equals("screen-size")) {
									width = Integer.parseInt(reader.getAttributeValue(0));
									height = Integer.parseInt(reader.getAttributeValue(1));
								} else if (reader.getLocalName().equals("response")) {
									rawGazes.add(getRawGaze(reader));
								} else {
									//do nothing
								}
							}
					
						}
						setRawGazes(rawGazes);
					} catch (XMLStreamException e) {
						throw new IOException("Could not read in data." +
								getFilterName() + ".");
					}
				}
			}
		}
	}
}
 
Example 20
Project: sstore-soft   File: FileUtil.java   View Source Code Vote up 2 votes
public static String getParentDirectory(String path) {

        File file = new File(path);

        return file.getParent();
    }