Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

How to Move a File in Java

Ramesh Fadatare edited this page Jul 18, 2018 · 2 revisions

Overview

Java.io.File does not contains any ready make move file method, but you can us renameTo() method to move a file.

Move File Example

  1. Create a file named "sample.txt" in directory "C:/workspace".
  2. Create File class object by passing file absolute location path "C:/workspace/sample.txt".
  3. We need to passs new abstract pathname to renameTo() method to move the file.
  4. renameTo() method returns true if and only if the renaming succeeded; false otherwise.
  5. Observe the directory whether the file is moved or not.
import java.io.File;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * This Java program demonstrates how to move file in Java.
 * @author javaguides.net
 */
public class MoveFileExample {
	private static final Logger LOGGER = LoggerFactory.getLogger(MoveFileExample.class);
	public static void main(String[] args) {
		moveFile();
	}
	public static void moveFile() {
		File file = new File("C:/workspace/sample.txt");
		boolean move = file.renameTo(new File("C:/workspace/moved/sample.txt"));
		if (move) {
			LOGGER.info("File is moved successful!");
		} else {
			LOGGER.info("File is failed to move!");
		}
	}
}

Reference

https://docs.oracle.com/javase/8/docs/api/java/io/File.html

Clone this wiki locally

AltStyle によって変換されたページ (->オリジナル) /