Java File Touch touch(String file)

Here you can find the source of touch(String file)

Description

Touches a file, so that it's timestamp is right now.

License

Apache License

Return

true if the touch succeeded, false otherwise

Declaration

public static boolean touch(String file) 

Method Source Code

//package com.java2s;
/*// w w  w  . ja  va 2  s .c o  m
 * Copyright 2010 dorkbox, llc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

public class Main {
    /**
     * Touches a file, so that it's timestamp is right now. If the file is not created, it will be created automatically.
     *
     * @return true if the touch succeeded, false otherwise
     */
    public static boolean touch(String file) {
        long timestamp = System.currentTimeMillis();
        return touch(new File(file).getAbsoluteFile(), timestamp);
    }

    /**
     * Touches a file, so that it's timestamp is right now. If the file is not created, it will be created automatically.
     *
     * @return true if the touch succeeded, false otherwise
     */
    public static boolean touch(File file) {
        long timestamp = System.currentTimeMillis();
        return touch(file, timestamp);
    }

    /**
     * Touches a file, so that it's timestamp is right now. If the file is not created, it will be created automatically.
     *
     * @return true if the touch succeeded, false otherwise
     */
    public static boolean touch(File file, long timestamp) {
        if (!file.exists()) {
            boolean mkdirs = file.getParentFile().mkdirs();
            if (!mkdirs) {
                // error creating the parent directories.
                return false;
            }

            try {
                new FileOutputStream(file).close();
            } catch (IOException ignored) {
                return false;
            }
        }

        return file.setLastModified(timestamp);
    }
}

Related

  1. touch(final File folder, final String fileName)
  2. touch(String _filename)
  3. touch(String answers)
  4. touch(String f)
  5. touch(String file)
  6. touch(String fileName)
  7. touch(String filePath)
  8. touch(String fullFilePath)
  9. touch(String name)