Created
February 2, 2015 19:54
-
-
Save ansig/0ca68706d35545e2386f to your computer and use it in GitHub Desktop.
Create, copy, move and delete a file using NIO.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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