Example usage for java.io File getAbsoluteFile

List of usage examples for java.io File getAbsoluteFile

Introduction

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

Prototype

public File getAbsoluteFile() 

Source Link

Document

Returns the absolute form of this abstract pathname.

Usage

From source file:com.vmware.identity.interop.PlatformUtils.java

private static boolean renameFileOnWindows(File oldFile, File newFile) {
    String sCurrentLine = "";

    try {//from   w  w  w  .  j a v  a 2s .  c  o m
        BufferedReader bufReader = new BufferedReader(new FileReader(oldFile.getAbsoluteFile()));
        BufferedWriter bufWriter = new BufferedWriter(new FileWriter(newFile.getAbsoluteFile()));

        while ((sCurrentLine = bufReader.readLine()) != null) {
            bufWriter.write(sCurrentLine);
            bufWriter.newLine();
        }
        bufReader.close();
        bufWriter.close();
        oldFile.delete();

        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:com.sap.prd.mobile.ios.mios.FileUtils.java

/**
 * /*www. j ava2  s.c o m*/
 * @param parent
 *          The parent directory
 * @param child
 *          The child direcory
 * @return the part of the path that represents the delta between <code>parent</code> and
 *         <code>child</code>.
 * @throws IllegalStateExcpetion
 *           in case <code>child</code> is not a child of <code>parent</code>.
 */
public static String getDelta(File parent, File child) {

    final List<String> _parent = split(parent.getAbsoluteFile());
    final List<String> _child = split(child.getAbsoluteFile());

    if (!isChild(_parent, _child))
        throw new IllegalStateException(
                "Child directory '" + child + "' is not a child of the base directory '" + parent + "'.");

    StringBuilder path = new StringBuilder();

    int index = getNumberOfCommonElements(_parent, _child);

    for (int size = _child.size(); index < size; index++) {

        if (path.length() != 0)
            path.append(File.separator);
        path.append(_child.get(index));
    }

    return path.toString();
}

From source file:FileUtils.java

/**
 * Read the contents of the specified file.
 * @param file The file to read./*w ww.  j  av  a  2  s .  co  m*/
 * @return The file contents.
 * @throws IOException Error readiong file.
 */
public static byte[] readFile(File file) throws IOException {

    if (!file.exists()) {
        throw new IllegalArgumentException("No such file '" + file.getAbsoluteFile() + "'.");
    } else if (file.isDirectory()) {
        throw new IllegalArgumentException(
                "File '" + file.getAbsoluteFile() + "' is a directory.  Cannot read.");
    }

    InputStream stream = new FileInputStream(file);
    try {
        return StreamUtils.readStream(stream);
    } finally {
        stream.close();
    }
}

From source file:com.hpe.application.automation.bamboo.tasks.TestResultHelperAlm.java

private static List<String> findRequiredStringsFromFile(BuildLogger logger, File resultFile) {
    List<String> results = new ArrayList<String>();
    try {/*  w  w w. ja v a2 s.co  m*/
        StringBuilder sb = new StringBuilder();
        BufferedReader in = new BufferedReader(new FileReader(resultFile.getAbsoluteFile()));
        try {
            String s;
            while ((s = in.readLine()) != null) {
                sb.append(s);
            }
        } finally {
            in.close();
        }
        //report link example: td://Automation.AUTOMATION.mydph0271.hpswlabs.adapps.hp.com:8080/qcbin/TestLabModule-000000003649890581?EntityType=IRun&amp;EntityID=1195091
        String sp = "td://.+?;EntityID=[0-9]+";
        Pattern p = Pattern.compile(sp);
        Matcher m = p.matcher(sb.toString());
        while (m.find()) {
            results.add(m.group());
        }
    } catch (Exception e) {
        logger.addBuildLogEntry(e.getMessage());
    }
    return results;
}

From source file:com.bc.util.io.FileUtils.java

public static boolean isSymbolicLink(File file) throws IOException {
    if (file == null) {
        throw new IllegalArgumentException("File cannot be null");
    }//from  w  w w.  java2s .c  o  m

    //next line dereferences symbolic links along the path.
    //eg. if path is /tmp/somedir/linktosomewhere/filename
    // and /tmp/somedir/linktosomewhere is a link to /tmp/somedir2
    // then this file is now /tmp/somedir2/filename
    File parentFile = file.getParentFile();
    if (parentFile != null) {
        file = new File(parentFile.getAbsoluteFile().getCanonicalFile(), file.getName());
    }

    File absoluteFile = file.getAbsoluteFile();
    String canonicalPath = absoluteFile.getCanonicalPath();
    String absolutePath = file.getAbsolutePath();

    //if the absolute canonical path is the same as the absolute path, we don't believe it is a link
    return !canonicalPath.equals(absolutePath);

    //org.apache.commons.io.FileUtils is supposed to have a method for this, but the versions in maven (1.3, 1.3.1, 1.4) don't seem to.
    //return org.apache.commons.io.FileUtils.isSymlink(file);
}

From source file:de.thischwa.pmcms.tool.file.FileTool.java

/**
 * Recursive file collector./*from w  ww.j  a v a  2  s  . c  o  m*/
 * 
 * @param dir
 *            Directory to start with.
 * @param filesToCollect
 *            {@link List} to hold the collected {@link File}s
 * @param filter
 *            Optional {@link FilenameFilter}, can be null.
 */
private static void collect(final File dir, List<File> filesToCollect, final FilenameFilter filter) {
    List<File> dirList = new ArrayList<File>();
    List<File> fileList = new ArrayList<File>();
    File[] files = (filter != null) ? dir.listFiles(filter) : dir.listFiles();

    for (File file : files) {
        if (file.isDirectory())
            dirList.add(file.getAbsoluteFile());
        else
            fileList.add(file.getAbsoluteFile());
    }
    Collections.sort(fileList);
    Collections.sort(dirList);

    filesToCollect.addAll(fileList);

    for (File subdir : dirList)
        collect(subdir.getAbsoluteFile(), filesToCollect, filter);
}

From source file:FileUtils.java

public static void writeFile(byte[] bytes, File file) throws IOException {
    if (file.isDirectory()) {
        throw new IllegalArgumentException(
                "File '" + file.getAbsoluteFile() + "' is an existing directory.  Cannot write.");
    }/*from  w  ww .  j av  a2 s. c  o  m*/

    FileOutputStream stream = new FileOutputStream(file);
    try {
        stream.write(bytes);
        stream.flush();
    } finally {
        stream.close();
    }
}

From source file:Functions.FileUpload.java

public static boolean processFile(String path, FileItemStream item, String houseId, String owner) {
    if ("".equals(item.getName())) {
        return false;
    }//from w  w  w .j  a v a  2s  .  c  o  m
    String nm = houseId + item.getName();
    System.out.println("nm =====================" + nm);
    try {
        File f = new File(path + File.separator + "images/");

        if (!f.exists()) {//den uparxei kan o fakelos opote den einai sthn database tpt!
            System.out.println("Mphke sthn if den exists");
            f.mkdir();
            File savedFile = new File(f.getAbsoluteFile() + File.separator + nm);
            FileOutputStream fos = new FileOutputStream(savedFile);
            InputStream is = item.openStream();
            int x = -1;
            byte b[] = new byte[1024];
            while ((x = is.read(b)) != -1) {
                fos.write(b, 0, x);
                //fos.write(x);
            }
            fos.flush();
            fos.close();
            database_common_functions.insertIntoBaseImage(houseId, nm);

            return true;
        } else {
            System.out.println("Mphke sthn if exists");
            if (database_common_functions.isHouseImageInDatabase(houseId, nm) == 1) {
                //overwrites current image with name nm.
                System.out.println("Mphke na kanei overwrite t arxeio");
                FileOutputStream fos = new FileOutputStream(f.getAbsoluteFile() + File.separator + nm);
                InputStream is = item.openStream();
                int x = -1;
                byte b[] = new byte[1024];
                while ((x = is.read(b)) != -1) {
                    fos.write(b, 0, x);
                    //fos.write(x);
                }
                fos.flush();
                fos.close();
                return true;
            } else {

                FileOutputStream fos = new FileOutputStream(f.getAbsoluteFile() + File.separator + nm);
                InputStream is = item.openStream();
                int x = -1;
                byte b[] = new byte[1024];
                while ((x = is.read(b)) != -1) {
                    fos.write(b, 0, x);
                    //fos.write(x);
                }
                fos.flush();
                fos.close();
                database_common_functions.insertIntoBaseImage(houseId, nm);
                return true;
            }

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

From source file:com.extjs.JSBuilder2.java

private static void openProjectFile(String projectFileName) {
    try {//from  w w w .  j  a  v  a  2s .c  o  m
        System.out.println(projectFileName);

        File inputFile = new File(projectFileName);
        projectHome = inputFile.getAbsoluteFile().getParent();

        /* read the file into a string */
        String s = FileHelper.readFileToString(inputFile);

        /* create json obj from string */
        projCfg = new JSONObject(s);
        System.out.format("Loading the '%s' Project%n", projCfg.get("projectName"));
    } catch (Exception e) {
        System.err.println(e.getMessage());
        System.err.println("Failed to open project file.");
    }
}

From source file:com.example.SampleStreamExample.java

public static void run(String consumerKey, String consumerSecret, String token, String secret)
        throws InterruptedException {
    // Create an appropriately sized blocking queue
    BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10000);

    // Define our endpoint: By default, delimited=length is set (we need this for our processor)
    // and stall warnings are on.
    StatusesSampleEndpoint endpoint = new StatusesSampleEndpoint();
    endpoint.stallWarnings(false);// ww w  .  j  a v a  2  s .  co  m

    File file = new File("/usr/local/Output11.txt");

    if (!file.exists()) {
        try {
            file.createNewFile();
            FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("[");
            bw.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    Authentication auth = new OAuth1(consumerKey, consumerSecret, token, secret);
    //Authentication auth = new com.twitter.hbc.httpclient.auth.BasicAuth(username, password);

    // Create a new BasicClient. By default gzip is enabled.
    BasicClient client = new ClientBuilder().name("sampleExampleClient").hosts(Constants.STREAM_HOST)
            .endpoint(endpoint).authentication(auth).processor(new StringDelimitedProcessor(queue)).build();

    // Establish a connection
    client.connect();

    // Do whatever needs to be done with messages
    for (int msgRead = 0; msgRead < 1000; msgRead++) {
        if (client.isDone()) {
            System.out.println("Client connection closed unexpectedly: " + client.getExitEvent().getMessage());
            break;
        }

        String msg = queue.poll(5, TimeUnit.SECONDS);
        //  String Time="time",Text="Text";
        //Lang id;
        if (msg == null) {
            System.out.println("Did not receive a message in 5 seconds");
        } else {

            System.out.println(msg);
            //System.out.println("**************hahahahahahahah********************");

            try {
                FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
                BufferedWriter bw = new BufferedWriter(fw);

                if (msgRead == 999)
                    bw.write(msg);
                else
                    bw.write(msg + ",");

                bw.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            /*     JSONParser jsonParser = new JSONParser();
                   //JsonElement jsonElement = null;
                           
                   String key="";
                try {
                   //jsonElement= (JsonElement) jsonParser.parse(msg); 
                 JSONObject jsonObject = (JSONObject) jsonParser.parse(msg);
                 //JsonObject jsonObjec = jsonElement.getAsJsonObject();
                 //for(Entry<String, JsonElement> entry : jsonObjec.entrySet())
              //   {  key = entry.getKey();
                 //   if(key=="delete")
                    //      System.out.println("this comment is deleted");
              //   }   
                   //JsonElement value = entry.getValue();
                         
                 //***** printing date
              //   Time = (String) jsonObject.get("created_at");
                    System.out.println("Date of creation====: " + jsonObject.get("created_at"));
                    //******printing id
                  //   id = (Lang) jsonObject.get("id");
                 //   System.out.println("id=========: " + jsonObject.get("id"));
                    //*******text
                     //Text = (String) jsonObject.get("text");
                   //System.out.println("Text==========: " + jsonObject.get("text"));
                            
                    //************inside user************
                    JSONObject structure = (JSONObject) jsonObject.get("user");
                    System.out.println("Into user structure ,  id====: " + structure.get("id"));
                    System.out.println("Into user structure ,  name====: " + structure.get("name"));
                    System.out.println("Into user structure ,  screen_name====: " + structure.get("screen_name"));
                    System.out.println("Into user structure ,  location====: " + structure.get("location"));
                    System.out.println("Into user structure ,  description====: " + structure.get("description"));
                    System.out.println("Into user structure ,  followers====: " + structure.get("followers_count"));
                    System.out.println("Into user structure ,  friends====: " + structure.get("friends_count"));
                    System.out.println("Into user structure ,  listed====: " + structure.get("listed_count"));
                    System.out.println("Into user structure ,  favorite====: " + structure.get("favorites_count"));
                    System.out.println("Into user structure ,  status_count====: " + structure.get("status_count"));
                    System.out.println("Into user structure ,  created at====: " + structure.get("created at"));
                            
                            
                            
                         
              } catch (ParseException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
              }
                    
                  */
        }
    }
    FileWriter fw;
    try {
        fw = new FileWriter(file.getAbsoluteFile(), true);
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write("]");
        bw.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    client.stop();

    // Print some stats
    System.out.printf("The client read %d messages!\n", client.getStatsTracker().getNumMessages());

}