Java Examples for java.io.File

The following java examples will help you to understand the usage of java.io.File. These source code samples are taken from different open source projects.

Example 1
Project: platform-api-master  File: Runner.java View source code
@Override
public void run() {
    try {
        memoryAllocator.allocate();
        final java.io.File downloadDir = Files.createTempDirectory(deployDirectory.toPath(), ("download_" + getName().replace("/", "."))).toFile();
        final DeploymentSources deploymentSources = createDeploymentSources(request, downloadDir);
        process.addToCleanupList(downloadDir);
        if (!getDeploymentSourcesValidator().isValid(deploymentSources)) {
            throw new RunnerException(String.format("Unsupported project. Cannot deploy project %s from workspace %s with runner %s", request.getProject(), request.getWorkspace(), getName()));
        }
        final ApplicationProcess realProcess = newApplicationProcess(deploymentSources, runnerCfg);
        realProcess.start();
        process.started(realProcess);
        watcher.start(new Cancellable() {

            @Override
            public void cancel() throws Exception {
                process.getLogger().writeLine("[ERROR] Your run has been shutdown due to timeout.");
                process.internalStop(true);
            }
        });
        runningAppsCounter.incrementAndGet();
        LOG.debug("Started {}", process);
        final long endTime = System.currentTimeMillis();
        LOG.debug("Application {}/{} startup in {} ms", request.getWorkspace(), request.getProject(), (endTime - startTime));
        realProcess.waitFor();
        process.stopped();
        LOG.debug("Stopped {}", process);
    } catch (Throwable e) {
        LOG.warn(e.getMessage(), e);
        process.setError(e);
    } finally {
        watcher.stop();
        memoryAllocator.release();
        runningAppsCounter.decrementAndGet();
    }
}
Example 2
Project: checkstyle-master  File: AvoidStaticImportCheckTest.java View source code
@Test
public void testDefaultOperation() throws Exception {
    final DefaultConfiguration checkConfig = createCheckConfig(AvoidStaticImportCheck.class);
    final String[] expected = { "23: " + getCheckMessage(MSG_KEY, "java.io.File.listRoots"), "25: " + getCheckMessage(MSG_KEY, "javax.swing.WindowConstants.*"), "26: " + getCheckMessage(MSG_KEY, "javax.swing.WindowConstants.*"), "27: " + getCheckMessage(MSG_KEY, "java.io.File.createTempFile"), "28: " + getCheckMessage(MSG_KEY, "java.io.File.pathSeparator"), "29: " + getCheckMessage(MSG_KEY, "com.puppycrawl.tools.checkstyle.checks.imports." + "InputAvoidStaticImportNestedClass.InnerClass"), "30: " + getCheckMessage(MSG_KEY, "com.puppycrawl.tools.checkstyle.checks.imports." + "InputAvoidStaticImportNestedClass.InnerClass.one") };
    verify(checkConfig, getPath("InputAvoidStaticImport.java"), expected);
}
Example 3
Project: sosies-generator-master  File: DirectoryWalkerTestCase.java View source code
/** 
     * Test Filtering
     */
@Test(timeout = 1000)
public void testFilter_add1183() {
    fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(), this, "testFilter_add1183");
    List<java.io.File> results = new TestFileFinder(dirsAndFilesFilter, 2).find(javaDir);
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 1979, (((1 + (org.apache.commons.io.DirectoryWalkerTestCase.dirs.length)) + (org.apache.commons.io.DirectoryWalkerTestCase.ioFiles.length)) + (org.apache.commons.io.DirectoryWalkerTestCase.outputFiles.length)));
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 1981, results, 1980, results.size());
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 1983, results, 1982, results.contains(org.apache.commons.io.DirectoryWalkerTestCase.javaDir));
    checkContainsFiles("Dir", dirs, results);
    checkContainsFiles("Dir", dirs, results);
    checkContainsFiles("IO File", ioFiles, results);
    checkContainsFiles("Output File", outputFiles, results);
    fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread());
}
Example 4
Project: korsakow-editor-master  File: FileExternalVideoEncoder.java View source code
public void encode(VideoCodec srcFormat, File srcFile, File destFile) throws EncoderException, InterruptedException {
    Process process = null;
    try {
        process = createProcess(srcFormat, srcFile, destFile);
    } catch (IOException e) {
        throw new VideoEncoderException(e, srcFile);
    }
    encode(process, srcFile, destFile);
}
Example 5
Project: Desktop-master  File: DirectoryFileFilter.java View source code
public boolean accept(File file) {
    if (file.isDirectory()) {
        List<String> subfolders = getStringList(DocearController.getPropertiesController().getProperty("docear_subdirs_to_ignore", null));
        for (String subfolder : subfolders) {
            if (file.getName().equals(subfolder)) {
                return false;
            }
        }
        return true;
    } else {
        return false;
    }
}
Example 6
Project: dk-master  File: FileFormatUtil.java View source code
/**
	 * 判断文件是否正确
	 * @param file 上传文件
	 * @param fileName 文件名称
	 * @return
	 * @throws Exception
	 */
public static String fileIsTrue(File file, String fileName) throws Exception {
    if (file == null) {
        return "请上传文件!";
    }
    if (!file.exists()) {
        return "文件不存在";
    }
    //从后面查找
    int lastIndex = fileName.lastIndexOf(".");
    String suffix = fileName.substring(//截取
    lastIndex + //截取
    1);
    if (!"XLS".equalsIgnoreCase(suffix)) {
        return "文件格式不正确";
    }
    return null;
}
Example 7
Project: openjdk8-jdk-master  File: Test.java View source code
private static void copyFile(String pBaseDir, String pArchiveName, int pIndex) {
    try {
        java.io.File lSource = new java.io.File(pBaseDir, pArchiveName);
        java.io.File lDestination = new java.io.File(pBaseDir, pIndex + pArchiveName);
        if (!lDestination.exists()) {
            lDestination.createNewFile();
            java.io.InputStream lInput = new java.io.FileInputStream(lSource);
            java.io.OutputStream lOutput = new java.io.FileOutputStream(lDestination);
            byte[] lBuffer = new byte[1024];
            int lLength = -1;
            while ((lLength = lInput.read(lBuffer)) > 0) {
                lOutput.write(lBuffer, 0, lLength);
            }
            lInput.close();
            lOutput.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 8
Project: openjdk-master  File: Abort.java View source code
public static void main(String... args) throws Exception {
    String SCRATCH_DIR = System.getProperty("user.dir");
    JavaCompiler javacTool = ToolProvider.getSystemJavaCompiler();
    java.io.File testDir = new java.io.File(SCRATCH_DIR);
    sourceA.dumpTo(testDir);
    sourceB.dumpTo(testDir);
    DiagnosticChecker diagChecker = new DiagnosticChecker();
    JavacTask ct = (JavacTask) javacTool.getTask(null, null, diagChecker, Arrays.asList("-XDrawDiagnostics", "-cp", testDir.getAbsolutePath()), null, Arrays.asList(sourceA.asJFO(testDir)));
    try {
        ct.analyze();
    } catch (Throwable ex) {
    }
    if (!diagChecker.errorFound) {
        throw new AssertionError("Missing diagnostic");
    }
}
Example 9
Project: jdk7u-jdk-master  File: Test.java View source code
private static void copyFile(String pBaseDir, String pArchiveName, int pIndex) {
    try {
        java.io.File lSource = new java.io.File(pBaseDir, pArchiveName);
        java.io.File lDestination = new java.io.File(pBaseDir, pIndex + pArchiveName);
        if (!lDestination.exists()) {
            lDestination.createNewFile();
            java.io.InputStream lInput = new java.io.FileInputStream(lSource);
            java.io.OutputStream lOutput = new java.io.FileOutputStream(lDestination);
            byte[] lBuffer = new byte[1024];
            int lLength = -1;
            while ((lLength = lInput.read(lBuffer)) > 0) {
                lOutput.write(lBuffer, 0, lLength);
            }
            lInput.close();
            lOutput.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 10
Project: ManagedRuntimeInitiative-master  File: Test.java View source code
private static void copyFile(String pBaseDir, String pArchiveName, int pIndex) {
    try {
        java.io.File lSource = new java.io.File(pBaseDir, pArchiveName);
        java.io.File lDestination = new java.io.File(pBaseDir, pIndex + pArchiveName);
        if (!lDestination.exists()) {
            lDestination.createNewFile();
            java.io.InputStream lInput = new java.io.FileInputStream(lSource);
            java.io.OutputStream lOutput = new java.io.FileOutputStream(lDestination);
            byte[] lBuffer = new byte[1024];
            int lLength = -1;
            while ((lLength = lInput.read(lBuffer)) > 0) {
                lOutput.write(lBuffer, 0, lLength);
            }
            lInput.close();
            lOutput.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 11
Project: securereader-master  File: EPubMediaContentPreviewView.java View source code
@Override
public void setMediaContent(MediaContent mediaContent, File mediaFile, java.io.File mediaFileNonVFS, boolean useThisThread) {
    mMediaContent = mediaContent;
    mMediaFile = mediaFileNonVFS;
    if (mMediaFile == null) {
        Log.v("EPubMediaContentPreviewView", "Failed to download media, no file.");
        return;
    }
}
Example 12
Project: erlide-master  File: MD5Checksum.java View source code
public static String getMD5(final File file) throws Exception {
    try (final FileInputStream f = new FileInputStream(file)) {
        final byte[] buffer = new byte[1024];
        final MessageDigest digest = MessageDigest.getInstance("MD5");
        int numRead;
        while ((numRead = f.read(buffer)) != -1) {
            digest.update(buffer, 0, numRead);
        }
        return new String(digest.digest());
    }
}
Example 13
Project: schach-master  File: ListReader.java View source code
public static ArrayList<String> loadStrings(File aFile) {
    ArrayList<String> pVec = new ArrayList<String>();
    if (!aFile.exists())
        return pVec;
    try {
        BufferedReader pReader = new BufferedReader(new FileReader(aFile));
        String pLine;
        while ((pLine = pReader.readLine()) != null) {
            pLine = pLine.trim();
            if (pLine.startsWith("#") || pLine.equals(""))
                continue;
            pVec.add(pLine);
        }
        pReader.close();
    } catch (IOException aE) {
        aE.printStackTrace();
    }
    return pVec;
}
Example 14
Project: osmdroid-master  File: FolderFileCounter.java View source code
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
/**
	 * @return <code>true</code> on success, <code>false</code> otherwise.
	 */
public static int getTotalRecursiveFileCount(final File pFolder) {
    final File[] children = pFolder.listFiles();
    int tmpCnt = 0;
    for (final File c : children) {
        if (c.isDirectory()) {
            tmpCnt += getTotalRecursiveFileCount(c);
        } else {
            tmpCnt++;
        }
    }
    return tmpCnt;
}
Example 15
Project: ilarkesto-master  File: AScmTool.java View source code
public AScmProject getProject(File projectDir) {
    if (!projectDir.exists())
        throw new RuntimeException("Project does not exist: " + projectDir.getPath());
    if (!isProjectDir(projectDir))
        throw new RuntimeException("Not a " + getName() + " project: " + projectDir.getPath());
    return createProject(projectDir);
}
Example 16
Project: fdroidclient-master  File: CleanCacheService21.java View source code
static void deleteIfOld(File file, long olderThan) {
    try {
        StructStat stat = Os.lstat(file.getAbsolutePath());
        if ((stat.st_atime * 1000L) < olderThan) {
            file.delete();
        }
    } catch (ErrnoException e) {
        e.printStackTrace();
    }
}
Example 17
Project: QEditor-master  File: TedFontActivity.java View source code
/**
	 * Set the result of this activity to open a file
	 * 
	 * @param file
	 *            the file to return
	 * @return if the result was set correctly
	 */
protected boolean setOpenResult(File file) {
    Intent result;
    if (!file.canRead()) {
        Crouton.showText(this, R.string.toast_file_cant_read, Style.ALERT);
        return false;
    }
    result = new Intent();
    result.setData(Uri.fromFile(file));
    setResult(RESULT_OK, result);
    return true;
}
Example 18
Project: MUtils-master  File: FileModifiedComparator.java View source code
@Override
public int compare(File lhs, File rhs) {
    long diff = lhs.lastModified() - rhs.lastModified();
    if (diff > 0) {
        return mOrder == Order.ASC ? 1 : -1;
    } else if (diff < 0) {
        return mOrder == Order.ASC ? -1 : 1;
    } else {
        return 0;
    }
}
Example 19
Project: open-mika-master  File: FileTest.java View source code
/**
     * @tests java.io.File#File(java.io.File, java.lang.String)
    @TestTargetNew(
        level = TestLevel.PARTIAL_COMPLETE,
        notes = "",
        method = "File",
        args = {java.io.File.class, java.lang.String.class}
    )
     */
public void test_ConstructorLjava_io_FileLjava_lang_String() {
    // Regression test for HARMONY-21
    File path = new File("/dir/file");
    File root = new File("/");
    File file = new File(root, "/dir/file");
    assertEquals("Assert 1: wrong path result ", path.getPath(), file.getPath());
    assertFalse("Assert 1.1: path absolute ", new File("\\\\\\a\b").isAbsolute());
    assertTrue("Assert 1.1: path absolute ", new File("///a/b").isAbsolute());
    // Test data used in a few places below
    String dirName = System.getProperty("java.io.tmpdir");
    String fileName = "input.tst";
    // change user.dir to a folder that's writeable on android.
    String oldUserDir = System.getProperty("user.dir");
    System.setProperty("user.dir", dirName);
    // Check filename is preserved correctly
    File d = new File(dirName);
    File f = new File(d, fileName);
    if (!dirName.regionMatches((dirName.length() - 1), File.separator, 0, 1)) {
        dirName += File.separator;
    }
    dirName += fileName;
    assertTrue("Assert 2: Created incorrect file " + f.getPath(), f.getPath().equals(dirName));
    // Check null argument is handled
    try {
        f = new File(d, null);
        fail("Assert 3: NullPointerException not thrown.");
    } catch (NullPointerException e) {
    }
    f = new File((File) null, fileName);
    assertEquals("Assert 4: Created incorrect file " + f.getPath(), dirName, f.getAbsolutePath());
    // Regression for HARMONY-46
    File f1 = new File("a");
    File f2 = new File("a/");
    assertEquals("Assert 5: Trailing slash file name is incorrect", f1, f2);
    // reset user.dir
    System.setProperty("user.dir", oldUserDir);
}
Example 20
Project: googleplaycrawler-master  File: FileResponse.java View source code
// get file as http response
private void getFileAsHttpResponse(java.io.File f) throws FileException, IOException {
    // ignore file of size larger than
    // Integer.MAX_VALUE = 2^31-1 = 2147483647
    long size = f.length();
    if (size > Integer.MAX_VALUE) {
        throw new FileException("file is too large, size: " + size);
    // or we can do this?
    // this.code = 400; // http Bad request
    // return;
    }
    // capture content
    int len = (int) size;
    if (this.file.maxContentLength >= 0 && len > this.file.maxContentLength)
        len = this.file.maxContentLength;
    this.content = new byte[len];
    java.io.InputStream is = new java.io.FileInputStream(f);
    int offset = 0;
    int n = 0;
    while (offset < len && (n = is.read(this.content, offset, len - offset)) >= 0) {
        offset += n;
    }
    if (offset < len) {
        // keep whatever already have, but issue a warning
        if (File.LOG.isWarnEnabled()) {
            File.LOG.warn("not enough bytes read from file: " + f.getPath());
        }
    }
    is.close();
    // set headers
    headers.set(Response.CONTENT_LENGTH, new Long(size).toString());
    headers.set(Response.LAST_MODIFIED, HttpDateFormat.toString(f.lastModified()));
    String mimeType = MIME.getMimeType(f);
    headers.set(Response.CONTENT_TYPE, mimeType != null ? mimeType : "");
    // response code
    // http OK
    this.code = 200;
}
Example 21
Project: apache-nutch-fork-master  File: FileResponse.java View source code
// get file as http response
private void getFileAsHttpResponse(java.io.File f) throws FileException, IOException {
    // ignore file of size larger than
    // Integer.MAX_VALUE = 2^31-1 = 2147483647
    long size = f.length();
    if (size > Integer.MAX_VALUE) {
        throw new FileException("file is too large, size: " + size);
    // or we can do this?
    // this.code = 400;  // http Bad request
    // return;
    }
    // capture content
    int len = (int) size;
    if (this.file.maxContentLength >= 0 && len > this.file.maxContentLength)
        len = this.file.maxContentLength;
    this.content = new byte[len];
    java.io.InputStream is = new java.io.FileInputStream(f);
    int offset = 0;
    int n = 0;
    while (offset < len && (n = is.read(this.content, offset, len - offset)) >= 0) {
        offset += n;
    }
    if (offset < len) {
        // keep whatever already have, but issue a warning
        if (File.LOG.isWarnEnabled()) {
            File.LOG.warn("not enough bytes read from file: " + f.getPath());
        }
    }
    is.close();
    // set headers
    headers.set(Response.CONTENT_LENGTH, new Long(size).toString());
    headers.set(Response.LAST_MODIFIED, HttpDateFormat.toString(f.lastModified()));
    MimeType mimeType = MIME.getMimeType(f);
    String mimeTypeString = mimeType != null ? mimeType.getName() : "";
    headers.set(Response.CONTENT_TYPE, mimeTypeString);
    // response code
    // http OK
    this.code = 200;
}
Example 22
Project: jease-master  File: Transit.java View source code
public java.io.File getFile() {
    if (uri != null) {
        java.io.File file = new java.io.File(URI.create(uri));
        try {
            if (!file.exists()) {
                try {
                    file.getParentFile().mkdirs();
                    file.createNewFile();
                } catch (IOException e) {
                    throw new RuntimeException(e.getMessage(), e);
                }
            }
        } catch (RuntimeException e) {
            return null;
        }
        return file;
    } else {
        return null;
    }
}
Example 23
Project: Strata-master  File: MarketDataRootValidator.java View source code
@Override
public void validate(String name, File value) throws ParameterException {
    if (!value.exists()) {
        throw new ParameterException(Messages.format("Invalid market data root directory: {}", value.getAbsolutePath()));
    }
    if (!value.isDirectory()) {
        throw new ParameterException(Messages.format("Market data root must be a directory: {}", value.getAbsolutePath()));
    }
}
Example 24
Project: molgenis-master  File: JarRunnerImpl.java View source code
@Override
public File runJar(String outputFile, List<String> params, File inputVcf) throws IOException, InterruptedException {
    File outputVcf = File.createTempFile(outputFile, ".vcf");
    List<String> command = new ArrayList<>();
    command.add("java");
    command.add("-jar");
    command.addAll(params);
    command.add(inputVcf.getAbsolutePath());
    ProcessBuilder pb = new ProcessBuilder(command);
    pb.redirectOutput(outputVcf);
    // Error logging to standard logging.
    pb.redirectError(ProcessBuilder.Redirect.INHERIT);
    Process p = pb.start();
    p.waitFor();
    return outputVcf;
}
Example 25
Project: liferay-ide-master  File: Main.java View source code
public static void copyFile(File source, File dest) {
    try {
        FileChannel in = new FileInputStream(source).getChannel();
        if (!dest.getParentFile().exists())
            dest.getParentFile().mkdirs();
        FileChannel out = new FileOutputStream(dest).getChannel();
        in.transferTo(0, in.size(), out);
        in.close();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}