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

The following are Jave code examples for showing how to use getAbsolutePath() 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: call-IDE   File: InsMain.java   View Source Code Vote up 7 votes
/**
 * download submission or assignment from server
 * @param toDown assignment or submission to be downloaded
 */
private void downloadFrom(Assignment toDown ) {
    client.sendUTFDataToServer("DOWNLOAD_SUBS");
    client.sendObjectToServer(toDown);
    
    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.showOpenDialog(this);
    File downFolder = chooser.getSelectedFile();
    
    
    byte[] data = (byte[]) client.getObjectFromServer();
    try {
        fos = new FileOutputStream(downFolder.getAbsolutePath() + "/" + toDown.getName() + ".zip");
        fos.write(data);
        fos.close();
    } catch (IOException ex) {
        Logger.getLogger(StudentMain.class.getName()).log(Level.SEVERE, null, ex);
    }
    
    
}
 
Example 2
Project: OpenJSharp   File: FileSystemView.java   View Source Code Vote up 7 votes
public File getChild(File parent, String fileName) {
    if (fileName.startsWith("\\")
        && !fileName.startsWith("\\\\")
        && isFileSystem(parent)) {

        //Path is relative to the root of parent's drive
        String path = parent.getAbsolutePath();
        if (path.length() >= 2
            && path.charAt(1) == ':'
            && Character.isLetter(path.charAt(0))) {

            return createFileObject(path.substring(0, 2) + fileName);
        }
    }
    return super.getChild(parent, fileName);
}
 
Example 3
Project: smart-lens   File: TFUtils.java   View Source Code Vote up 7 votes
public static File getImageLabels(@Nullable Context context) {
    File dir = new File(FileUtils.getCacheDir(context).getAbsolutePath() + "/"
            + TF_CACHE_DIRECTORY);
    if (!dir.exists()) dir.mkdir();

    return new File(dir.getAbsolutePath() + "/"
            + "imagenet_comp_graph_label_strings.txt");
}
 
Example 4
Project: Android-DownloadManager   File: DownloadManager.java   View Source Code Vote up 6 votes
/**
 * Set the local destination for the downloaded file to a path within
 * the application's external files directory (as returned by
 * {@link Context#getExternalFilesDir(String)}.
 * <p>
 * The downloaded file is not scanned by MediaScanner. But it can be
 * made scannable by calling {@link #allowScanningByMediaScanner()}.
 *
 * @param context the {@link Context} to use in determining the external
 *            files directory
 * @param dirType the directory type to pass to
 *            {@link Context#getExternalFilesDir(String)}
 * @param subPath the path within the external directory, including the
 *            destination filename
 * @return this object
 * @throws IllegalStateException If the external storage directory
 *             cannot be found or created.
 */
public Request setDestinationInExternalFilesDir(Context context, String dirType,
        String subPath) {
    final File file = context.getExternalFilesDir(dirType);
    if (file == null) {
        throw new IllegalStateException("Failed to get external storage files directory");
    } else if (file.exists()) {
        if (!file.isDirectory()) {
            throw new IllegalStateException(file.getAbsolutePath() +
                    " already exists and is not a directory");
        }
    } else {
        if (!file.mkdirs()) {
            throw new IllegalStateException("Unable to create directory: "+
                    file.getAbsolutePath());
        }
    }
    setDestinationFromBase(file, subPath);
    return this;
}
 
Example 5
Project: openjdk-jdk10   File: Utils.java   View Source Code Vote up 6 votes
static String getAjavaCmd(String cmdStr) {
    File binDir = new File(JavaHome, "bin");
    File unpack200File = IsWindows
            ? new File(binDir, cmdStr + ".exe")
            : new File(binDir, cmdStr);

    String cmd = unpack200File.getAbsolutePath();
    if (!unpack200File.canExecute()) {
        throw new RuntimeException("please check" +
                cmd + " exists and is executable");
    }
    return cmd;
}
 
Example 6
Project: OpenDA   File: OdsDll.java   View Source Code Vote up 6 votes
public OdsDll(String nativeDllPath) {

		if (dllYetToBeInitialized) {

			String actualNativeDllPath = "ods";
			if (nativeDllPath != null) {
				File nativeDllFileOrDir = new File(nativeDllPath);
				if (!nativeDllFileOrDir.exists()) {
					throw new RuntimeException("Invalid native DLL path: " + nativeDllFileOrDir.getAbsolutePath());
				}
				if (nativeDllFileOrDir.isDirectory()) {
					actualNativeDllPath = nativeDllPath + "/ods";
				} else {
					actualNativeDllPath = nativeDllPath;
					for (String ext : new String[]{ ".so", ".dll" }) {
						if (actualNativeDllPath.toLowerCase().endsWith(ext))
							actualNativeDllPath = actualNativeDllPath.substring(
									0, actualNativeDllPath.length() - ext.length());
					}
				}
			}

			// Delft3D-Flow uses ifort for both linux and windows.
			// If in the future another compiler is needed, e.g. gfortran,
			// see org.openda.model_efdc_dll.EfdcDLL for an example of function name mapping.
			if(BBUtils.RUNNING_ON_WINDOWS){
				odsWinIfortDll = (OdsWinIfortDll) Native.loadLibrary(actualNativeDllPath, OdsWinIfortDll.class);

			}else{
				// GfortranFunctionMapper gFortranMapper = new GfortranFunctionMapper();
				// HashMap<String, String> gFortranMap = gFortranMapper.getMap();
				odsWinIfortDll = (OdsWinIfortDll) Native.loadLibrary(
						actualNativeDllPath, OdsWinIfortDll.class); // , gFortranMap);
			}
			dllYetToBeInitialized = true;
		}
	}
 
Example 7
Project: EvolvingNetLib   File: SDCardUtil.java   View Source Code Vote up 6 votes
/**
 * 往SDCard的私有File目录下保存文件
 *
 * @param data
 * @param type
 * @param filename
 * @param context
 * @return
 */
public static boolean saveData2SDCardPrivateFileDir(byte[] data, String type, String filename, Context context) {
    if (isSDCardMounted()) {
        File path = context.getExternalFilesDir(type);
        if (!path.exists()) {
            path.mkdir();
        }
        String file = path.getAbsolutePath() + File.separator + filename;
        try {
            OutputStream os = new FileOutputStream(file);
            os.write(data);
            os.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return false;
}
 
Example 8
Project: Accessibility   File: FileUtils.java   View Source Code Vote up 6 votes
private static void createNewFile(File file_) {
    if (file_ == null) {
        return;
    }
    if (!(__createNewFile(file_)))
        throw new RuntimeException(file_.getAbsolutePath()
                + " doesn't be created!");
}
 
Example 9
Project: revolution-irc   File: ChatLogStorageManager.java   View Source Code Vote up 6 votes
private long getBlockSize() {
    if (mBlockSize == 0L) {
        File chatLogDir = mServerConfigManager.getChatLogDir();
        if (!chatLogDir.exists())
            return 0L;
        StatFs statFs = new StatFs(chatLogDir.getAbsolutePath());
        if (Build.VERSION.SDK_INT >= 18)
            mBlockSize = statFs.getBlockSizeLong();
        else
            mBlockSize = statFs.getBlockSize();
    }
    return mBlockSize;
}
 
Example 10
Project: medialibrary   File: GalleryUtils.java   View Source Code Vote up 6 votes
public static String searchDirForPath(File dir, int bucketId) {
    File[] files = dir.listFiles();
    if (files != null) {
        for (File file : files) {
            if (file.isDirectory()) {
                String path = file.getAbsolutePath();
                if (GalleryUtils.getBucketId(path) == bucketId) {
                    return path;
                } else {
                    path = searchDirForPath(file, bucketId);
                    if (path != null) return path;
                }
            }
        }
    }
    return null;
}
 
Example 11
Project: aos-FileCoreLibrary   File: ZipFile2.java   View Source Code Vote up 5 votes
/**
 * This method does access the actual storage to get data about the file
 */
public ZipFile2(File file) {
    if (file == null)
        throw new IllegalArgumentException("file must not be null");

    //remove file://
    if(file.getAbsolutePath().startsWith("file://"))
        mPath = file.getAbsolutePath().substring("file://".length());
    else
        mPath = file.getAbsolutePath();
    mLength = file.length();
    mIsFile = file.isFile();
    mLastModified = file.lastModified();
}
 
Example 12
Project: wirtualnaApteczka   File: AddMedicineActivity.java   View Source Code Vote up 5 votes
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK) {
        switch (requestCode) {
            case AppConstants.REQUEST_IMAGE_CAPTURE:
                try {
                    PhotoDescriptionTO photoDescriptionTO = currentMedicine.getPhotoDescriptionTO();

                    File fullSizePhoto = new File(photoDescriptionTO.getFullSizePhotoUri());
                    File smallSizePhoto = PhotoUtils.prepareSmallSizePhotoFile(fullSizePhoto);
                    String smallSizePhotoAbsolutePath = smallSizePhoto.getAbsolutePath();
                    photoDescriptionTO.setSmallSizePhotoUri(smallSizePhotoAbsolutePath);

                    setMedicineThumbnail(photoDescriptionTO);
                } catch (Exception e) {
                    // Had to remove logs, becasue of google play
                }
                break;
            case AppConstants.REQUEST_VOICE_INPUT_MEDICINE_NAME:
                String potentialMedicineName = retrievePotentialMedicineNameFromVoiceRecognizedData(data);

                if (!TextUtils.isEmpty(potentialMedicineName)) {
                    nameEdit.setText(potentialMedicineName);
                }
                break;
            case AppConstants.REQUEST_VOICE_INPUT_MEDICINE_NOTES:
                String potentialMedicineNotes = retrievePotentialMedicineNameFromVoiceRecognizedData(data);

                if (!TextUtils.isEmpty(potentialMedicineNotes)) {
                    notesEdit.setText(potentialMedicineNotes);
                }
                break;
            default:
                break;
        }
    }
}
 
Example 13
Project: Cognizant-Intelligent-Test-Scripter   File: CsvDataProvider.java   View Source Code Vote up 5 votes
@Override
public CsvTestData importTestData(File file) {
    CsvTestData csvData = new CsvTestData(file.getAbsolutePath());
    csvData.loadTableModel();
    csvData.setLocation(getLocation() + File.separator + file.getName());
    csvData.saveChanges();
    return csvData;
}
 
Example 14
Project: Android-Hotpatch   File: Hotpatch.java   View Source Code Vote up 5 votes
public void loadLibrary(String jarpath, Context context) {
    this.context = context;

    File jarfile = new File(jarpath);
    if(!jarfile.exists())
        throw new IllegalArgumentException("Could not find library: " + jarpath);

    this.jarpath = jarpath;

    File optimizedLibrarypath = context.getDir("dex", 0);

    dexClassLoader = new DexClassLoader(jarpath, optimizedLibrarypath.getAbsolutePath(),
                                        null, context.getClassLoader());

}
 
Example 15
Project: cythara   File: PipeDecoder.java   View Source Code Vote up 4 votes
public PipeDecoder(){
	pipeBuffer = 10000;

	//Use sensible defaults depending on the platform
	if(System.getProperty("os.name").indexOf("indows") > 0 ){
		pipeEnvironment = "cmd.exe";
		pipeArgument = "/C";
	}else if(new File("/bin/bash").exists()){
		pipeEnvironment = "/bin/bash";
		pipeArgument = "-c";
	}else if (new File("/system/bin/sh").exists()){
		//probably we are on android here
		pipeEnvironment = "/system/bin/sh";
		pipeArgument = "-c";
	}else{
		LOG.severe("Coud not find a command line environment (cmd.exe or /bin/bash)");
		throw new Error("Decoding via a pipe will not work: Coud not find a command line environment (cmd.exe or /bin/bash)");
	}
	
	String path = System.getenv("PATH");
	String arguments = " -ss %input_seeking%  %number_of_seconds% -i \"%resource%\" -vn -ar %sample_rate% -ac %channels% -sample_fmt s16 -f s16le pipe:1";
	if(isAvailable("ffmpeg")){
		LOG.info("found ffmpeg on the path (" + path + "). Will use ffmpeg for decoding media files.");
		pipeCommand = "ffmpeg" + arguments;	
	}else if (isAvailable("avconv")){
		LOG.info("found avconv on your path(" + path + "). Will use avconv for decoding media files.");
		pipeCommand = "avconv" + arguments;
	}else {
		if(isAndroid()) {
			String tempDirectory = System.getProperty("java.io.tmpdir");
			printErrorstream=true;
			File f = new File(tempDirectory, "ffmpeg");
			if (f.exists() && f.length() > 1000000 && f.canExecute()) {
				decoderBinaryAbsolutePath = f.getAbsolutePath();
			} else {
				LOG.severe("Could not find an ffmpeg binary for your Android system. Did you forget calling: 'new AndroidFFMPEGLocator(this);' ?");
				LOG.severe("Tried to unpack a statically compiled ffmpeg binary for your architecture to: " + f.getAbsolutePath());
			}
		}else{
			LOG.warning("Dit not find ffmpeg or avconv on your path(" + path + "), will try to download it automatically.");
			FFMPEGDownloader downloader = new FFMPEGDownloader();
			decoderBinaryAbsolutePath = downloader.ffmpegBinary();
			if(decoderBinaryAbsolutePath==null){
				LOG.severe("Could not download an ffmpeg binary automatically for your system.");
			}
		}
		if(decoderBinaryAbsolutePath == null){
			pipeCommand = "false";
			throw new Error("Decoding via a pipe will not work: Could not find an ffmpeg binary for your system");
		}else{
			pipeCommand = '"' + decoderBinaryAbsolutePath + '"' + arguments;
		}
	}
}
 
Example 16
Project: hadoop   File: TestDistributedShell.java   View Source Code Vote up 4 votes
@Test(timeout=90000)
public void testDSShellWithShellScript() throws Exception {
  final File basedir =
      new File("target", TestDistributedShell.class.getName());
  final File tmpDir = new File(basedir, "tmpDir");
  tmpDir.mkdirs();
  final File customShellScript = new File(tmpDir, "custom_script.sh");
  if (customShellScript.exists()) {
    customShellScript.delete();
  }
  if (!customShellScript.createNewFile()) {
    Assert.fail("Can not create custom shell script file.");
  }
  PrintWriter fileWriter = new PrintWriter(customShellScript);
  // set the output to DEBUG level
  fileWriter.write("echo testDSShellWithShellScript");
  fileWriter.close();
  System.out.println(customShellScript.getAbsolutePath());
  String[] args = {
      "--jar",
      APPMASTER_JAR,
      "--num_containers",
      "1",
      "--shell_script",
      customShellScript.getAbsolutePath(),
      "--master_memory",
      "512",
      "--master_vcores",
      "2",
      "--master_gcores",
      "0",
      "--container_memory",
      "128",
      "--container_vcores",
      "1",
      "--container_gcores",
      "0"
  };

  LOG.info("Initializing DS Client");
  final Client client =
      new Client(new Configuration(yarnCluster.getConfig()));
  boolean initSuccess = client.init(args);
  Assert.assertTrue(initSuccess);
  LOG.info("Running DS Client");
  boolean result = client.run();
  LOG.info("Client run completed. Result=" + result);
  List<String> expectedContent = new ArrayList<String>();
  expectedContent.add("testDSShellWithShellScript");
  verifyContainerLog(1, expectedContent, false, "");
}
 
Example 17
Project: graphflow   File: UDFResolver.java   View Source Code Vote up 4 votes
/**
 * @param pathToJar The absolute path to the jar file containing the user's {@link UDFAction}
 * class.
 * @param udfClassName The qualified class name for the udf in the jar file.
 *
 * @throws IOException when the jar file cannot be read or accessed.
 * @throws ClassNotFoundException when the class specified is not found in the specified jar.
 * @throws InstantiationException When the class loaded from the jar fails to be instantiated.
 * @throws IllegalAccessException when the application has no access to the definition of the
 * specified class.
 */
public static UDFAction getUDFObject(String pathToJar, String udfClassName) throws IOException,
    ClassNotFoundException, IllegalAccessException, InstantiationException {
    File file = new File(pathToJar);
    URL[] urls = {new URL("jar:file:" + file.getAbsolutePath() + "!/")};
    URLClassLoader classLoader = URLClassLoader.newInstance(urls);
    @SuppressWarnings("rawtypes")
    Class classLoaded = classLoader.loadClass(udfClassName);
    return (UDFAction) classLoaded.newInstance();
}
 
Example 18
Project: parabuild-ci   File: DisplayChart.java   View Source Code Vote up 4 votes
/**
 * Service method.
 *
 * @param request  the request.
 * @param response  the response.
 *
 * @throws ServletException ??.
 * @throws IOException ??.
 */
public void service(HttpServletRequest request, 
                    HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession();
    String filename = request.getParameter("filename");

    if (filename == null) {
        throw new ServletException("Parameter 'filename' must be supplied");
    }

    //  Replace ".." with ""
    //  This is to prevent access to the rest of the file system
    filename = ServletUtilities.searchReplace(filename, "..", "");

    //  Check the file exists
    File file = new File(System.getProperty("java.io.tmpdir"), filename);
    if (!file.exists()) {
        throw new ServletException("File '" + file.getAbsolutePath() 
                + "' does not exist");
    }

    //  Check that the graph being served was created by the current user
    //  or that it begins with "public"
    boolean isChartInUserList = false;
    ChartDeleter chartDeleter = (ChartDeleter) session.getAttribute(
            "JFreeChart_Deleter");
    if (chartDeleter != null) {
        isChartInUserList = chartDeleter.isChartAvailable(filename);
    }

    boolean isChartPublic = false;
    if (filename.length() >= 6) {
        if (filename.substring(0, 6).equals("public")) {
            isChartPublic = true;
        }
    }
    
    boolean isOneTimeChart = false;
    if (filename.startsWith(ServletUtilities.getTempOneTimeFilePrefix())) {
        isOneTimeChart = true;   
    }

    if (isChartInUserList || isChartPublic || isOneTimeChart) {
        //  Serve it up
        ServletUtilities.sendTempFile(file, response);
        if (isOneTimeChart) {
            file.delete();   
        }
    }
    else {
        throw new ServletException("Chart image not found");
    }
    return;
}
 
Example 19
Project: DecompiledMinecraft   File: DedicatedServer.java   View Source Code Vote up 4 votes
/**
 * Returns the filename where server properties are stored
 */
public String getSettingsFilename()
{
    File file1 = this.settings.getPropertiesFile();
    return file1 != null ? file1.getAbsolutePath() : "No settings file";
}
 
Example 20
Project: QN-ACTR-Release   File: Dispatcher_jSIMschema.java   View Source Code Vote up 2 votes
/**
 * This constructor receives the absolute path of the xml file containing
 * the model to be solved.
 * The model must be described using the SIMmodeldefinition.xsd schema
 *
 * @param model the xml file containing the
 * model to be solved
 */
public Dispatcher_jSIMschema(File model) {
	simModelDefinition = model;
	simModelDefinitionPath = model.getAbsolutePath();
}