














Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!















// Create a file objectFile file = new File(
"filename");
// Convert the file object to a URLURL url = null;try {
// The file need not exist.url = file.toURL(); // file:/d:/almanac1.4/java.io/filename } catch (MalformedURLException e) { }// Convert the URL to a file objectfile = new File(url.getFile()); // d:/almanac1.4/java.io/filename// Read the file contents using the URLtry {
// Open an input streamInputStream is = url.openStream();// Read from isis.close(); } catch (IOException e) { // Could not open the file }
File file = new File(
file = file.getAbsoluteFile(); // c:\temp\filename.txtfile = new File(
file = file.getAbsoluteFile(); // c:\temp\dir\filename.txtfile = new File(
file = file.getAbsoluteFile(); // c:\temp..\filename.txt// Note that filename.txt does not need to exist
// Get the parent of a relative filename path File file = new File(
"Ex1.java");
String parentPath = file.getParent(); // nullFile parentDir = file.getParentFile(); // null // Get the parents of an absolute filename path file = new File(
"D:\almanac\Ex1.java");
parentPath = file.getParent(); // D:\almanacparentDir = file.getParentFile(); // D:\almanacparentPath = parentDir.getParent(); // D:\parentDir = parentDir.getParentFile(); // D:\parentPath = parentDir.getParent(); // nullparentDir = parentDir.getParentFile(); // null
File dir = new File(
"directoryName");
boolean isDir = dir.isDirectory();if (isDir){
// dir is a directory } else{
// dir is a file }
boolean exists = (new File(
if (exists){
// File or directory exists } else{
// File or directory does not exist }
try{
File file = new File(
// Create file if it does not existboolean success = file.createNewFile();if (success){
// File did not exist and was created } else{
// File already exists } } catch (IOException e) { }
File file = new File(
// Get the number of bytes in the filelong length = file.length();
// File (or directory) with old nameFile file = new File(
// File (or directory) with new nameFile file2 = new File(
// Rename file (or directory)boolean success = file.renameTo(file2);if (!success){
// File was not successfully renamed }
// File (or directory) to be movedFile file = new File(
// Destination directoryFile dir = new File(
// Move file to new directoryboolean success = file.renameTo(new File(dir, file.getName()));if (!success){
// File was not successfully moved }
String curDir = System.getProperty("user.dir");