I have a JAVA program to display the contents of a folder: files, folders and the contents of the subfolders.
public static void displayContent(File curFolder, int indent){
if(curDir.isFile()){
System.out.println(curDir.getName());
} else if(curDir.isFolder()){
System.out.println(curDir.getName());
if(curDir.length() > 0){
for(File file: curDir.listFiles()){
displayContent(file, indent + 4);
}
}
}
}
I created a test folder with a bunch of subfolders to test my program and it runs very well. But when I use my program to test system folders such as "C:\Users", it returns a lot of unexpected results:
It displays some folders I cannot find in the folder, such as "All users", "Application Data". Plus they are not hidden files.
Some folders and files do exist, but they do not show in my results. The name of the folder containing these files begins with a dot, such as ".android". What is this type of folder? How do I deal with it?
My OS is windows 8; IDE is NetBeans 8.0.
I'm pretty sure you want to print the path instead of printing the name. That way you can see the folder structure. Also, your code seems to have a fairly large number of typos,
public static void displayContent(File curDir, int indent) { // <-- curDir used below
if (curDir.isFile()) {
System.out.println(curDir.getPath());
} else if (curDir.isDirectory()) {
System.out.println(curDir.getPath());
for (File file : curDir.listFiles()) {
displayContent(file, indent + 4); // <-- displayContent not displayContents.
}
}
}
Related
This question already has answers here:
How do I move a file from one location to another in Java?
(11 answers)
Closed 6 years ago.
i'm trying in a loop to move files after they are loaded and processed...when I test moving file part individually it works but when I do it all at once it does not work.
Bellow works fine, but moves directories also but I want only the file to be moved.
public class moveFiles {
public static void main(String[] args) {
String getFilesFrom = "D:\\show\\from";
String destDir = "D:\\show\\to\\";
File srcFile = new File(getFilesFrom);
srcFile.renameTo(new File(destDir, srcFile.getName()));
}
}
The code that I have which is not working the moving part is bellow.
for (File child : file.listFiles()) {
if(extensionFilter.accept(child)) {
fr = new FileReader(child);
cm.copyIn("COPY ct"+addExtraZero+month+" FROM STDIN WITH DELIMITER ',' csv", fr);
} else {
System.out.println("No File is elgible to be loaded");
break;
}
getNumberOfFilesProcessed++;
System.out.println("Loading now " + child.getName());
child.renameTo(new File(moveFilesTo, child.getName()));
}
System.out.println("Number of files Loaded is: " + getNumberOfFilesProcessed);
The above code is:
get files from source directory,
loaded it in database
print files name that it loads
get count of files loaded
which all above works but the last part which is to move files to other directory after loading is not working bellow is the section of files that suppose to move the file the loop.
child.renameTo(new File(moveFilesTo, child.getName()));
scratching my heads for two hours any help will be appreciated.
From description of File.renameTo() (emphasis mine):
The rename operation might not be able to move a file from one
filesystem to another, it might not be atomic, and it might not
succeed if a file with the destination abstract pathname already
exists. The return value should always be checked to make sure that
the rename operation was successful
Add:
if( !child.renameTo(new File(moveFilesTo, child.getName())) )
System.out.println("Could not move file");
Or try using move(Path, Path, CopyOption...) method, as this has more options (using File.toPath()).
I am not asking how to check if a file exists or how to check if a file is in a specific directory level. Rather I want to know how to check if an existing file is anywhere underneath a specified directory.
Obviously if a file is a direct child of a directory that is easy to check. But what I want to be able to do is efficiently check if an existing file is in a directory including any possible subdirectory. I'm using this in an Android project where I am keeping fine grain control over my cache and I want a utility method to check if a file I may be manipulating is in my cache folder.
Example:
cache dir
/ \
dir file1
/ \
file2 file3
isCacheFile(file2) should return true
Currently I have a method that does it like so
private static final File cacheDir = AssetManager.getInstance().getCacheDir(); // Not android.content.res.AssetManager
private static final String cacheDirName = cacheDir.getAbsolutePath();
public static boolean isCacheFile(File f) {
if (!f.exists()) return false;
return f.getAbsolutePath().startsWith(cacheDirName);
}
However, I am inclined to believe there is a better way to do this. Does anyone have any suggestions?
If you have a known path (in the form of File f), and you want to know if it is inside a particular folder (in the form of File cacheDir), you could simply traverse the chain of parent folders of your file and see if you meet the one you are looking for.
Like this:
public static boolean isCacheFile(File f) {
while (f.getParentDir()!=null) {
f = f.getParentDir();
if (f.equals(cacheDir)) {
return true;
}
}
return false;
}
boolean isContains(File directory){
File[] contents = directory.listFiles();
if (contents != null) {
for(int i = 0; i < contents.length; i++){
if(contents[i].isDirectory())
isContains(contents[i]);
else if(contents[i].getName().equals(*your_file_name*))
return true;
}
}
return false;
}
You could do it by recursion, by calling if the file exists in each sub-directory.
first check if the file exists in the root directory.
boolean exist = new File(rootDirectory, temp).exists();
then if the file wasn't in the root directory, then list all the files and call the method again in the sub-directoy files recursionally until you find the file or there are no more sub-directories.
public String getPathFromFileName(String dirToStart,Sring fileName){
File f = new File(dirToStart);
File[] list = f.listFiles();
String s="null";
for(int i=0;i<list.length;i++){
if(list[i].isFile()){
//is a file
if(fileName.equals(list[i])){
s=dirToStart+"/"+fileName;
break;
}
}else{
//is a directory search further.
getPathFromFileName(dirToStart+list[i]);
}
}
return s;
}
call this method by passing the parent directory name and the file name to search in subdirectories.
you check the return value if it is not equal to "null", then the files path is returned.
I have one folder which contains many sub-folders. To make it more clear here is an example of the folders:
Movies:
MovieTitle:
Moviefile.mp4 (Movie File)
MovieSubtitles.srt (Subtitles)
MovieSeries:
MovieTitle:
Moviefile.mp4
MovieSubtitles.srt
I need to rename each mp4 and srt file to the following "MovieTitle". If the movie is part of a series it should be named to Series "Title + Movie Title". Lets use Star Wars as an example for series and how to name. "Star Wars" would be the name of a directory in "Movies". In "Star Wars" are 6 Folders each with a mp4 and srt file in it. For episode 1 of star wars the mp4 and srt file should be renamed to: "Star Wars - Episode 1.mp4" and "Star Wars - Episode 1.srt". If Episode 1 was not part of series it should be named to just "Episode 1.mp4"
Here is the code that I have come up with so far:
public static void renaming(File[] files){
String dir1, dir2;
for(File movie: files){ //Main folder containing all of the movies.
dir1 = movie.getName();
for(File filesInMovie: movie.listFiles()){
if(filesInMovie.isDirectory()){ //This means that it is a series.
dir2 = filesInMovie.getName();
for(File i: filesInMovie.listFiles()){
i.renameTo(dir1 + " - " + dir2);
}
}else{
filesInMovie.renameTo(dir1)
}
}
}
}
I realize that renameTo is an actual function in Java. I thought it would rename files until I read what it actually does (which I am still a little fuzzy on). So my main question is how would I get this code to properly rename the files.
Just some extra things you should know:
One Directory Contains all of the movies.
There are possibilities for each folder in the movies folder
It has other folders in it (It is a series)
It has a mp4 and srt file in it
If you have any questions please ask!!!
File#getName() returns a String. You are using this to get the name of the current file and then attempting to rename the file using File#rename(String) where the method is actually defined as File#renameTo(File). That is it the argument is expected to be a file to where you are attempting to rename the file.
Some Suggestions:
Look at Files.move() use this to move the file to target - Link has example of this
Don't use the get name method for the first directory - use the file directly (Something like below but still not correct I think) and this is if you want the file in the same base directory movies
i.renameTo(new File(movie," - " + filesInMovie.getName() + ext);
Still needs work for extension of file ext however which will come from the file i
Using Guava and Java 7, here is what you can do:
public final class Renamer
{
private static final Joiner JOINER = Joiner.on(" - ");
private static final class RenamerVisitor
extends SimpleFileVisitor<Path>
{
private final Path baseDir;
private RenamerVisitor(final Path baseDir)
{
this.baseDir = baseDir;
}
#Override
public FileVisitResult visitFile(final Path file,
final BasicFileAttributes attrs)
throws IOException
{
final Path relpath = baseDir.relativize(file);
final String targetName
= JOINER.join(Iterables.transform(relpath,
Functions.toStringFunction()));
final Path dstPath = baseDir.resolve(targetName);
System.out.printf("'%s' -> '%s'\n", file, dstPath);
return FileVisitResult.CONTINUE;
}
}
public static void main(final String... args)
throws IOException
{
final Path baseDir = Paths.get("/home/fge/tmp/jsr203/docs");
Files.walkFileTree(baseDir, new RenamerVisitor(baseDir));
}
}
This is for my environment in a directory. Sample output:
[...]
'/home/fge/tmp/jsr203/docs/java/io/class-use/File.html' -> '/home/fge/tmp/jsr203/docs/java - io - class-use - File.html'
'/home/fge/tmp/jsr203/docs/java/io/class-use/FilePermission.html' -> '/home/fge/tmp/jsr203/docs/java - io - class-use - FilePermission.html'
'/home/fge/tmp/jsr203/docs/java/io/File.html' -> '/home/fge/tmp/jsr203/docs/java - io - File.html'
In order to make it use the "real thing", replace the System.out.println() in visitFile with Files.move() and you're done!
Of course, you can also choose to copy instead, or even create a (hard) link if your filesystem supports it.
Side note: unlike File's .renameTo(), Files.move() does not silently fail!
(and after that, you should drop Java 6's old file API fast)
I need to delete all the files and folders in a directory but i need to .svn folder in this so that i can commit and delete the folder everytime. My below code worked but it retains .svn parent folder only but rest of its child .svn folders are deleted
my code:
if (pFile.exists() ) {
System.out.println(pFile.getName());
if (pFile.isDirectory()) {
if (pFile.list().length == 0) {
System.out.println("0>"+pFile.getName());
pFile.delete();
} else {
System.out.println("1>"+pFile.getName());
String[] strFiles = pFile.list();
for (String strFilename : strFiles) {
File fileToDelete = new File(pFile, strFilename);
System.out.println("2>"+fileToDelete.getName());
if(fileToDelete.getName()==".svn")
{
// Do Nothing
break;
}
else
{
delete(fileToDelete);
}
}
}
} else {
System.out.println("3>"+pFile.getName());
pFile.delete();
}
}
Need to modify condition as below. Here break will stop loop where as continue will skip only current deletion (ie, folder as .svn)
if(fileToDelete.getName()!=null && fileToDelete.getName().equals(".svn")){
// Do Nothing
continue;
}
You can use pFile.isHidden() to check if it is a hidden file.
In addition you can list all files in a folder with File.listFiles() instead of File.list() so you dont have to create a new File.
The other suggestions should solve your issue else you say, you need to delete all files and folders in a directory. So may be you are deleting all child folders that contain .svn in them and so you dont see them remain.
I'm trying to locate the directory of the offending font file per these instructions: http://devnet.jetbrains.com/docs/DOC-172
I am getting an error with the font name. I have searched and deleted matching files, however, but the script keeps throwing an error on the same font name. I suspect there's a hidden copy somewhere on Windows 7 and I'd like to add file directory information to the output.
Is there a way to obtain directory information about the file prior to the exception output? Or is java using something other than file directory structure to derive the list of fonts in the system?
import java.awt.Font;
import java.awt.GraphicsEnvironment;
public class FontTest {
public static void main(String[] args) {
Font[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
for (int i = 0; i < fonts.length; i++) {
final Font font = fonts[i];
final String name = font.getName();
System.out.print("Checking Font: " + name);
if (font.canDisplay('a') &&
font.canDisplay('z') &&
font.canDisplay('A') &&
font.canDisplay('Z') &&
font.canDisplay('0') &&
font.canDisplay('1')) {
System.out.println(" OK.");
} else {
System.out.println();
}
}
}
}
I figured this out. Windows 7 implements a slick UI for font management. However, this did not display the Adobe Type 1 fonts in the directory. I did a command-line directory inspection and then did a 'search' for one of the files I found. This finally gave me the directory in File Explorer and from there I was able to remove all the Type1 files. PHEW. Thanks!