Example usage for java.io File isFile

List of usage examples for java.io File isFile

Introduction

In this page you can find the example usage for java.io File isFile.

Prototype

public boolean isFile() 

Source Link

Document

Tests whether the file denoted by this abstract pathname is a normal file.

Usage

From source file:Main.java

private static boolean handleFile(int mode, byte[] key, byte[] iv, String sourceFilePath, String destFilePath) {

    File sourceFile = new File(sourceFilePath);
    File destFile = new File(destFilePath);

    try {//from www . java 2 s  . co  m
        if (sourceFile.exists() && sourceFile.isFile()) {
            if (!destFile.getParentFile().exists())
                destFile.getParentFile().mkdirs();
            destFile.createNewFile();

            InputStream in = new FileInputStream(sourceFile);
            OutputStream out = new FileOutputStream(destFile);
            Cipher cipher = initCipher(mode, key, iv, AES_CFB_NOPADDING);
            CipherInputStream cin = new CipherInputStream(in, cipher);

            byte[] b = new byte[1024];
            int read = 0;
            while ((read = cin.read(b)) != -1) {
                out.write(b, 0, read);
                out.flush();
            }

            cin.close();
            in.close();
            out.close();

            return true;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return false;
}

From source file:com.smart.common.FileHelper.java

/**
 * ?//  w w  w .j ava 2s .c om
 *
 * @param sPath ??
 * @return ??true?false
 */
public static void deleteFile(String sPath) {
    File file = new File(sPath);
    // ?
    if (file.isFile() && file.exists()) {
        file.delete();
    }
}

From source file:Main.java

public static boolean removeDir(File dir) {
    boolean flag = false;
    if (dir.exists() && dir.isDirectory()) {
        File[] childFiles = dir.listFiles();
        if (childFiles == null || childFiles.length == 0) {
            flag = dir.delete();//from   w w w  .  j  av a 2s.com
        } else {
            for (File child : childFiles) {
                boolean del = false;
                if (child.isDirectory()) {
                    del = removeDir(child);
                } else if (child.isFile()) {
                    del = child.delete();
                }
                if (!del) {
                    break;
                }
            }
            flag = dir.delete();
        }
    }
    return flag;
}

From source file:com.daphne.es.maintain.editor.web.controller.utils.CompressUtils.java

@SuppressWarnings("unchecked")
private static void unzipFolder(File uncompressFile, File descPathFile, boolean override) {

    ZipFile zipFile = null;/* w  w w  . j  a v  a2 s. co m*/
    try {
        zipFile = new ZipFile(uncompressFile, "GBK");

        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry zipEntry = entries.nextElement();
            String name = zipEntry.getName();
            name = name.replace("\\", "/");

            File currentFile = new File(descPathFile, name);

            //? 
            if (currentFile.isFile() && currentFile.exists() && !override) {
                continue;
            }

            if (name.endsWith("/")) {
                currentFile.mkdirs();
                continue;
            } else {
                currentFile.getParentFile().mkdirs();
            }

            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(currentFile);
                InputStream is = zipFile.getInputStream(zipEntry);
                IOUtils.copy(is, fos);
            } finally {
                IOUtils.closeQuietly(fos);
            }
        }
    } catch (IOException e) {
        throw new RuntimeException("", e);
    } finally {
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException e) {
            }
        }
    }

}

From source file:com.gsma.iariauth.validator.util.IARIValidatorMain.java

private static KeyStore loadKeyStore(String path, String password) {
    KeyStore ks = null;//from w  w w .ja  v  a 2s . com
    File certKeyFile = new File(path);
    if (!certKeyFile.exists() || !certKeyFile.isFile()) {
        return null;
    }
    char[] pass = password.toCharArray();
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(path);
        try {
            ks = KeyStore.getInstance("jks");
            ks.load(fis, pass);
        } catch (Exception e1) {
            try {
                ks = KeyStore.getInstance("bks", bcProvider);
                ks.load(fis, pass);
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    } catch (FileNotFoundException e) {
    } finally {
        try {
            if (fis != null)
                fis.close();
        } catch (Throwable t) {
        }
    }
    return ks;
}

From source file:com.googlecode.xmlzen.utils.FileUtils.java

/**
 * Reads a {@link File} and returns the contents as {@link String}
 * //from w w  w .  java2 s  .  c  o  m
 * @param file File to read
 * @param charset Charset of this File
 * @return File contents as String
 */
public static String readFile(final File file, final String charset) {
    InputStream in = null;
    try {
        if (!file.isFile()) {
            return null;
        }
        in = new FileInputStream(file);
        final BufferedInputStream buffIn = new BufferedInputStream(in);
        final byte[] buffer = new byte[(int) Math.min(file.length(), BUFFER)];
        int read;
        final StringBuilder result = new StringBuilder();
        while ((read = buffIn.read(buffer)) != -1) {
            result.append(new String(buffer, 0, read, charset));
        }
        return result.toString();
    } catch (final Exception e) {
        throw new XmlZenException("Failed reading file: " + file, e);
    } finally {
        close(in);
    }
}

From source file:com.asakusafw.compiler.bootstrap.OperatorCompilerDriver.java

private static File findSource(File sourcePath, Class<?> aClass) throws IOException {
    assert sourcePath != null;
    assert aClass != null;
    String[] segments = aClass.getName().split("\\."); //$NON-NLS-1$
    File current = sourcePath;/*from   w w  w . java2  s. c  o  m*/
    for (int i = 0; i < segments.length - 1; i++) {
        current = new File(current, segments[i]);
        if (current.isDirectory() == false) {
            throw new FileNotFoundException(MessageFormat.format("{0} (for {1})", current, aClass.getName()));
        }
    }
    String name = segments[segments.length - 1];
    int enclosing = name.indexOf('$');
    if (enclosing >= 0) {
        name = name.substring(0, enclosing);
    }
    File file = new File(current, name + ".java"); //$NON-NLS-1$
    if (file.isFile() == false) {
        if (current.isDirectory() == false) {
            throw new FileNotFoundException(MessageFormat.format("{0} (for {1})", file, aClass.getName()));
        }
    }
    return file.getCanonicalFile();
}

From source file:ict.servlet.UploadToServer.java

public static int upLoad2Server(String sourceFileUri) {
    String upLoadServerUri = "http://vbacdu.ddns.net:8080/WBS/newjsp.jsp";
    // String [] string = sourceFileUri;
    String fileName = sourceFileUri;
    int serverResponseCode = 0;

    HttpURLConnection conn = null;
    DataOutputStream dos = null;//from  w  ww . j a  va  2  s .  co  m
    DataInputStream inStream = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    String responseFromServer = "";

    File sourceFile = new File(sourceFileUri);
    if (!sourceFile.isFile()) {

        return 0;
    }
    try { // open a URL connection to the Servlet
        FileInputStream fileInputStream = new FileInputStream(sourceFile);
        URL url = new URL(upLoadServerUri);
        conn = (HttpURLConnection) url.openConnection(); // Open a HTTP  connection to  the URL
        conn.setDoInput(true); // Allow Inputs
        conn.setDoOutput(true); // Allow Outputs
        conn.setUseCaches(false); // Don't use a Cached Copy
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        conn.setRequestProperty("uploaded_file", fileName);
        dos = new DataOutputStream(conn.getOutputStream());

        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + fileName + "\""
                + lineEnd);
        dos.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available(); // create a buffer of  maximum size

        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

        while (bytesRead > 0) {
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        // Responses from the server (code and message)
        serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();

        m_log.info("Upload file to server" + "HTTP Response is : " + serverResponseMessage + ": "
                + serverResponseCode);
        // close streams
        m_log.info("Upload file to server" + fileName + " File is written");
        fileInputStream.close();
        dos.flush();
        dos.close();
    } catch (MalformedURLException ex) {
        //         ex.printStackTrace();
        m_log.error("Upload file to server" + "error: " + ex.getMessage(), ex);
    } catch (Exception e) {
        //      e.printStackTrace();
    }
    //this block will give the response of upload link
    /* try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String line;
      while ((line = rd.readLine()) != null) {
      m_log.info("Huzza" + "RES Message: " + line);
      }
      rd.close();
      } catch (IOException ioex) {
      m_log.error("Huzza" + "error: " + ioex.getMessage(), ioex);
      }*/
    return serverResponseCode; // like 200 (Ok)

}

From source file:io.apiman.test.common.util.TestUtil.java

/**
 * Loads a test plan from a file resource.
 * @param planFile//from   w w w. j a  v a2 s.c  om
 */
public static final TestPlan loadTestPlan(File planFile) {
    try {
        if (!planFile.isFile())
            throw new RuntimeException("Test Plan not found: " + planFile.getCanonicalPath()); //$NON-NLS-1$
        JAXBContext jaxbContext = JAXBContext.newInstance(TestPlan.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        TestPlan plan = (TestPlan) jaxbUnmarshaller.unmarshal(planFile);
        return plan;
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }
}

From source file:com.glaf.core.config.ViewProperties.java

public static void reload() {
    if (!loading.get()) {
        InputStream inputStream = null;
        try {//from   www .  j a  va  2s .com
            loading.set(true);
            String config = SystemProperties.getConfigRootPath() + "/conf/props/views";
            File directory = new File(config);
            if (directory.exists() && directory.isDirectory()) {
                String[] filelist = directory.list();
                if (filelist != null) {
                    for (int i = 0, len = filelist.length; i < len; i++) {
                        String filename = config + "/" + filelist[i];
                        File file = new File(filename);
                        if (file.isFile() && file.getName().endsWith(".properties")) {
                            inputStream = new FileInputStream(file);
                            Properties p = PropertiesUtils.loadProperties(inputStream);
                            if (p != null) {
                                Enumeration<?> e = p.keys();
                                while (e.hasMoreElements()) {
                                    String key = (String) e.nextElement();
                                    String value = p.getProperty(key);
                                    properties.setProperty(key, value);
                                    properties.setProperty(key.toLowerCase(), value);
                                    properties.setProperty(key.toUpperCase(), value);
                                }
                            }
                            IOUtils.closeStream(inputStream);
                        }
                    }
                }
            }
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        } finally {
            loading.set(false);
            IOUtils.closeStream(inputStream);
        }
    }
}