A file is the actual data located at a particular location on a disk. A filename is used to refer to the file. The name of the file can be changed without changing the data. The java.io.File class is closer to a filename than a file.
import java.io.File;
public class rls {
File dir;
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
rls r = new rls(args[i]);
r.list();
}
}
public rls(String s) {
dir = new File(s);
}
// This method doesn't do anything if dir isn't a directory
public void list() {
if (dir.isDirectory()) {
System.out.println("\n" + dir + ":\n");
String[] files = dir.list();
for (int i = 0; i < files.length; i++) {
System.out.println(files[i]);
}
for (int i = 0; i < files.length; i++) {
rls r = new rls(dir + File.separator + files[i]);
r.list();
}
}
}
}
This program can get stuck in an infinite loop if aliases or symbolic links point to a directory that's already been scanned. How would you fix this?
import java.io.File;
import java.io.IOException;
import java.applet.Applet;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.FileDialog;
public class FileInfo extends Applet {
TextArea info;
File theFile;
public static void main(String[] args) {
Frame f = new Frame("File Info");
FileInfo fi = new FileInfo();
f.add("Center", fi);
f.resize(200, 300);
fi.init();
f.show();
fi.start();
}
public void init() {
TextArea info = new TextArea(80, 40);
add(info);
}
public void start() {
FileDialog fd = new FileDialog(new Frame(), "Please choose a file: ", FileDialog.LOAD);
fd.show();
theFile = new File(fd.getFile());
showInfo();
}
public void showInfo() {
if (theFile.exists()) {
info.appendText("getName: " + theFile.getName());
info.appendText("getPath: " + theFile.getPath());
info.appendText("getAbsolutePath: " +
theFile.getAbsolutePath());
info.appendText("getParent: " + theFile.getParent());
if (theFile.canWrite()) info.appendText(theFile.getName() +
" is writable.");
if (theFile.canRead()) info.appendText(theFile.getName() +
" is readable.");
if (theFile.isFile()) {
info.appendText(theFile.getName() + " is a file.");
}
else if (theFile.isDirectory()) {
info.appendText(theFile.getName() + " is a directory.");
}
else {
info.appendText("What is this?");
}
if (theFile.isAbsolute()) {
info.appendText(theFile.getName() +
" is an absolute path.");
}
else {
info.appendText(theFile.getName() +
" is not an absolute path.");
}
info.appendText("Last Modified" + theFile.lastModified());
info.appendText(theFile.getName() + " is " + theFile.length() + " bytes.");
info.appendText(theFile.getName() + " is " + theFile.length() + " bytes.");
}
else {
info.appendText("I'm sorry. I can't find the file " + theFile);
}
}
}