Skip to content

Instantly share code, notes, and snippets.

@ansig
Created February 2, 2015 19:54
Show Gist options
  • Save ansig/0ca68706d35545e2386f to your computer and use it in GitHub Desktop.
Save ansig/0ca68706d35545e2386f to your computer and use it in GitHub Desktop.
Create, copy, move and delete a file using NIO.
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;
import static java.nio.file.StandardOpenOption.*;
import static java.nio.file.StandardCopyOption.*;
/**
* Create, copy, move and delete a file using NIO.
*/
public class NioTestClass {
static final Charset CHARSET = Charset.forName("UTF-8");
static List<Path> files = new ArrayList<>();
public static void main(String[] args) {
String text = "Lorem ipsum!";
Path filepath;
// Create a file
filepath = Paths.get("foo.txt");
try {
BufferedWriter writer = Files.newBufferedWriter(filepath, CHARSET, TRUNCATE_EXISTING, CREATE);
writer.write(text, 0, text.length());
writer.flush();
} catch (IOException ioe) {
System.err.printf("Could not create file: %s%n", ioe.getMessage());
}
files.add(filepath);
// Copy file
filepath = Paths.get("baz.txt");
try {
Files.copy(files.get(0), filepath, REPLACE_EXISTING);
} catch (NoSuchFileException nsfe) {
System.err.printf("No such file: %s%n", filepath);
} catch (IOException ioe) {
System.err.printf("Could not copy file: %s%n", ioe.getMessage());
}
files.add(filepath);
// Move file
filepath = Paths.get("baz.txt");
try {
Files.move(files.remove(0), filepath, REPLACE_EXISTING);
} catch (IOException ioe) {
System.err.printf("Could not move file: %s%n", ioe.getMessage());
}
files.add(filepath);
// Delete files
try {
for (Path fp : files) {
Files.deleteIfExists(fp);
}
} catch (IOException ioe) {
System.err.printf("Could not delete file: %s%n", ioe.getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment