Saturday, June 27, 2009

How to Read Text from a File


try {
BufferedReader in = new BufferedReader(new FileReader("C:/temp/temp.txt"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (IOException e) {
}

How to Read Text from Standard Input


try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String str = "";
while (str != null) {
str = in.readLine();
System.out.println(str);
}
} catch (IOException e) {
}

How to Delete a Directory


boolean success = (new File("directoryName")).delete();
if (success) {
// Deletion successful
}

How to Get the Current Working Directory


String currrentDirectory = System.getProperty("user.dir");

How to Rename a File


File oldFile = new File("C:/temp/oldTemp.txt");
File newFile = new File("C:/temp/newTemp.txt");
// Rename file
boolean success = oldFile.renameTo(newFile);
if (success) {
// File was successfully renamed
}

How Delete a File


boolean success = (new File("C:/temp/temp.txt")).delete();
if (success) {
// Deletion succeeded
}

How to Get the Size of a File


File file = new File("C:/temp/temp.txt");
// Get the number of bytes in the file
long length = file.length();

How to Determine If a File or Directory Exists


boolean existsFlag = (new File("C:/temp/temp.txt")).exists();
if (existsFlag) {
// File or directory exists
} else {
// File or directory does not exist
}

How to Create a File


try {
File file = new File("C:/temp/temp.txt");
} catch (IOException e) {
}

How to Determine If a File Path Is a File or a Directory


File file = new File("filepath");
boolean isDirectory = file.isDirectory();
if (isDirectory) {
// file is a directory
} else {
// file is a file
}

How to Get an Absolute File Path


File file = new File("C:"+File.separatorChar+"temp"+File.separatorChar+"temp.txt");
file = file.getAbsoluteFile(); // c:\temp\temp.txt

How to Construct a File Path


String path = File.separator +"temp"; // /temp
 

Sample Java Codes Copyright © 2008 Green Scrapbook Diary Designed by SimplyWP | Made free by Scrapbooking Software | Bloggerized by Ipiet Notez