In this article about File handling using Swing, I'll show how to work with the methods below:
- getName: return the file name;
- length: return the file lenght;
- exists: Check if the file exists;
- canRead: return true if the file can be read;
- canWrite: return true if the file can be write;
- renameTo: rename the file;
- isFile: Return true if the path is valid for a file;
- lastModified: Show date of last file change;
- delete: Delete the file;
Now let's create the methods above:
1-GetName ( )
1.1- Create a new button and set the "label" corresponding to his action, in our case "FileName":
1.2- Enter this code in commands package.
Listing 1: GetName
package commands;
import java.io.File;
public class FileName {
public String GetName(String fi){
File f = new File(fi);
if(!f.exists()){
System.out.println("File not found");
return "0";
}
return f.getName();
}
}
2-Length ( )
2.1- Create a new button and set the "label" corresponding to his action, in our case "size (length)":
2.2- Write this code in commands package:
Listing 2: Length
package commands;
import java.io.File;
public class FileSize {
public Integer GetSize(String fi){
File f = new File(fi);
if(!f.exists()){
System.out.println("File not found");
return 0;
}
return (int) f.length();
}
}
3-Exists ( )
3.1- Create a new button and set the "label" corresponding to his action, in our case "Exists?"
3.2- Write this code in commands package:
Listing 3: Exists
package commands;
import java.io.File;
public class IfExist {
public boolean exist(String file){
File f = new File(file);
if(!f.exists()){
System.out.println("File not found");
return false;
}
return true;
}
}
4-CanRead ( )
4.1- Create a new button and set the "label" corresponding to his action, in our case "Can Read?":
4.2- Write this code in commands package:
...
Exibição do post interrompida. Para ler conteúdo completo,
clique aqui