Examples, hints, and tips to help you code better in Java.
-
Delete a file or directory
Deleting a file or directory in Java is pretty simple. Create a
Fileobject and call the.delete()method on it.import java.io.File; File file = new File(filePath); file.delete();
The
.delete()method:
Returnstrueif the file/directory is deleted successfully
Returnsfalseif the file/directory is not deleted (ie. file not found, file is open)
Throws aSecurityExceptionif the application has insufficient permissions to delete the file/directory. -
Read a text file using readLine()
One of the simplest ways to read in a text file in Java is to use the
readLine()method to read one line at a time. In this example the file is opened with aFileReader, buffered with aBufferedReader, and then read in using thereadLine()method.import java.io.*; public class ReadTextFile { public static void main(String[] args) { StringBuilder contents = new StringBuilder(); try { BufferedReader input = new BufferedReader(new FileReader("C:\\Temp\\myFile.txt"));
-
For loop
This is an example of a typical for loop.
for( int var=0; var<10; var++) { // Code to execute }
The initiation of the for loop includes three different command seperated be semicolons.
First
In this example an integer namedvaris created and initialized to;
If we are using a variable that has already being instantiated just enter the name of the variable and optionally assign it a new value.
ie.
int var = 0; for(var=2; var<10; var++) { // Code to execute }
-
Hello World
A basic java program.
class HelloWorld { static public void main( String args[] ) { System.out.println( "Hello World!" ); } }
