How can I get duplicated values from ArrayList? - java

There is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public class CompareFile {
CompareFile() {}
boolean check = false;
int count = 0;
/*
* this method return a File type variable
* variable path - this parameter takes a path in specified root
* also it's a private method and he should be called with help by class object
*/
public File find(File path) throws FileNotFoundException {
PrintWriter writer = new PrintWriter("D:/Photos/name.txt");
ArrayList<String> buffer = new ArrayList<String>();
/*
* let's create array of files
* where must be all found files
* We use File[], and named 'files'
* variable files takes on list of found files
* with help by listFiles method, that
* return list of files and directories
*/
File[] files = path.listFiles();
//System.out.println(files.toString());
try {
/*
* we'll ought use the for each loop
* in this loop we'll create File type variable 'file'
* then we'll do iterating for each expression from variable files
*/
for (File file : files) {
//print all found files and directories
//if file or directory exists
if (file.isDirectory()) {
//recursively return file and directory
find(file);
}
else {
buffer.add(file.getName());
System.out.println(file);
}
}
}
catch (Exception e) {
System.out.print("Error");
}
finally{
if ( writer != null )
writer.close();
}
/*
Iterator<String> i = buffer.iterator();
while(i.hasNext()) {
System.out.println(i.next());
}*/
return path;
}
public static void main(String[] args) throws FileNotFoundException {
File mainFile = new File("D:/Photos/");
CompareFile main = new CompareFile();
main.find(mainFile);
}
}
If I use sort, after sorting, the result bad, because first row from dir "Photos",
and second row from directory in directory "Photos/sub" Let's look at
the screen: I think you understand)
http://s10.postimg.org/7hcw83z9x/image.png

You'll need to keep track of where you are in the tree, change the find method to take a path:
public File find(File path, string path="") throws FileNotFoundException
When you call the find method recursively:
find(file, path + file.getName() + "/")
Then when you add to the list, use
buffer.add(path + file.getName());

Related

How to compare all file names from a given directory java?

I want to compare all file names from a given directory
Input/Output code:
static Scanner sc = new Scanner(System.in);
static String Directory = sc.next();
static File folder = new File(Directory);
static File[]listofFiles = folder.listFiles();
static String[] underFiles = folder.list();
public static void main(String[] args) throws IOException {
Main main = new Main();
main.walk(Directory);
}
public void walk( String path ) {
File root = new File( path );
File[] list = root.listFiles();
if (list == null) {
return;
}
for (File f : list) {
if ( f.isDirectory() ) {
walk( f.getAbsolutePath() );
System.out.println( "Dir:" + f.getAbsoluteFile() );
}
else {
System.out.println( "File:" + f.getName() );
}
}
}
The input is to give a directory path. The output will show all of the files in the given directory. How can I compare equal file names in this directory?
As I understand it, you want to locate directories that contain files with the same file name. For example, on a Windows machine, you may have several folders that contain image files. Usually each one of those folders will have a file named Thumbs.db. So you would like to know the names of the folders that contain a file named Thumbs.db.
The following code calls method walk of class java.nio.file.Files and manipulates the Stream returned by that method to create a Map where the Map key is the file name and the Map value is a List of all the folders that contain a file with that name.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class WalkTree {
public static void main(String[] args) {
Path path = Paths.get(args[0]);
try (Stream<Path> paths = Files.walk(path)) {
Map<Path, List<Path>> map = paths.filter(p -> Files.isRegularFile(p))
.collect(Collectors.toMap(p -> p.getFileName(),
p -> new ArrayList<Path>(List.of(p.getParent())),
(l1, l2) -> {l1.addAll(l2); return l1;}));
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
The first parameter to the toMap method, in the above code, is a Function that returns the Map key. The second parameter is another Function that returns the Map value. And the third parameter is a BinaryOperator that merges two different Map values that both have the same Map key.
Try this:
public static void main(String[] args) throws IOException {
String path = "/your/file-path/here";
try (Stream<Path> paths = Files.walk(Paths.get(path))) {
Map<String, List<Path>> map =
paths.filter(Files::isRegularFile)
.collect(groupingBy(p -> p.getFileName().toString()));
System.out.println(map);
}
}
Files.walk will walk all the hierarchy of files for you. The only thing you need to do is to consume the Paths from Stream.
If you still want to stick with your own code. Then you might do this instead:
public static void walk(String path, Map<String, List<String>> map) {
File root = new File(path);
File[] list = root.listFiles();
if (list == null) return;
for (File f : list) {
if (f.isDirectory()) {
walk(f.getAbsolutePath(), map);
System.out.println("Dir:" + f.getAbsoluteFile());
} else {
map.computeIfAbsent(f.getName(), k -> new ArrayList())
.add(f.getAbsolutePath());
System.out.println("File:" + f.getName());
}
}
}
and then:
public static void main(String[] args) {
String fileName = "/your/file-path/here";
Map<String, List<String>> map = new HashMap<>();
walk(fileName, map);
System.out.println(map);
}

Java copy files matching pattern from many folders to another folder

Please take a look at the code I have so far and if possible explain what I'm doing wrong. I'm trying to learn.
I made a little program to search for a type of file in a directory and all its sub-directories and copy them into another folder.
Code
import java.util.ArrayList;
import java.util.List;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
public class FandFandLoop {
public static void main(String[] args) {
final File folder = new File("C:/Users/ina/src");
List<String> result = new ArrayList<>();
search(".*\\.txt", folder, result);
File to = new File("C:/Users/ina/dest");
for (String s : result) {
System.out.println(s);
File from = new File(s);
try {
copyDir(from.toPath(), to.toPath());
System.out.println("done");
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void copyDir(Path src, Path dest) throws IOException {
Files.walk(src)
.forEach(source -> {
try {
Files.copy(source, dest.resolve(src.relativize(source)),
StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
});
}
public static void search(final String pattern, final File folder, List<String> result) {
for (final File f : folder.listFiles()) {
if (f.isDirectory()) {
search(pattern, f, result);
}
if (f.isFile()) {
if (f.getName().matches(pattern)) {
result.add(f.getAbsolutePath());
}
}
}
}
}
It works, but what it actually does is to take my .txt files and write them into another file named dest without extension.
And at some point, it deletes the folder dest.
The deletion happens because of StandardCopyOption.REPLACE_EXISTING, if I understand this, but what I would have liked to obtain was that if several files had the same name then only one copy of it should be kept.
There is no need to call Files.walk on the matched source files.
You can improve this code by switching completely to using java.nio.file.Path and not mixing string paths and File objects. Additionally instead of calling File.listFiles() recursively you can use Files.walk or even better Files.find.
So you could instead use the following:
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.CopyOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Objects;
import java.util.function.BiPredicate;
import java.util.stream.Stream;
public class CopyFiles {
public static void copyFiles(Path src, Path dest, PathMatcher matcher, CopyOption... copyOptions) throws IOException {
// Argument validation
if (!Files.isDirectory(src)) {
throw new IllegalArgumentException("Source '" + src + "' is not a directory");
}
if (!Files.isDirectory(dest)) {
throw new IllegalArgumentException("Destination '" + dest + "' is not a directory");
}
Objects.requireNonNull(matcher);
Objects.requireNonNull(copyOptions);
BiPredicate<Path, BasicFileAttributes> filter = (path, attributes) -> attributes.isRegularFile() && matcher.matches(path);
// Use try-with-resources to close stream as soon as it is not longer needed
try (Stream<Path> files = Files.find(src, Integer.MAX_VALUE, filter)) {
files.forEach(file -> {
Path destFile = dest.resolve(src.relativize(file));
try {
copyFile(file, destFile, copyOptions);
}
// Stream methods do not allow checked exceptions, have to wrap it
catch (IOException ioException) {
throw new UncheckedIOException(ioException);
}
});
}
// Wrap UncheckedIOException; cannot unwrap it to get actual IOException
// because then information about the location where the exception was wrapped
// will get lost, see Files.find doc
catch (UncheckedIOException uncheckedIoException) {
throw new IOException(uncheckedIoException);
}
}
private static void copyFile(Path srcFile, Path destFile, CopyOption... copyOptions) throws IOException {
Path destParent = destFile.getParent();
// Parent might be null if dest is empty path
if (destParent != null) {
// Create parent directories before copying file
Files.createDirectories(destParent);
}
Files.copy(srcFile, destFile, copyOptions);
}
public static void main(String[] args) throws IOException {
Path srcDir = Paths.get("path/to/src");
Path destDir = Paths.get("path/to/dest");
// Could also use FileSystem.getPathMatcher
PathMatcher matcher = file -> file.getFileName().toString().endsWith(".txt");
copyFiles(srcDir, destDir, matcher);
}
}

Java File exists Case sensitive .jpg and .JPG

I use this function to detect if my file exists or not. While I have some image stored as .jpg, .JPG, .png, and .PNG. But it always return .jpg or .png as true even if the real file has extension .JPG or .PNG.
After I render it to my webpage it throws an error "Failed to load resource: the server responded with a status of 404 (Not Found)".
public static String getPhotoFileExtension(int empKey){
try{
String[] types = {".jpg",".JPG",".png", ".PNG"};
for(String t : types)
{
String path = "/"+Common.PHOTO_PATH + empKey + t;
File f = new File(Sessions.getCurrent().getWebApp()
.getRealPath(path));
if(f.isFile())
return t;
}
}catch (Exception e) {
e.printStackTrace();
}
return "";
}
So you want to get the real case sensitive names of files stored in your filesystem. Lets imaging we have the following paths:
on Linux: using ext4 (which is case sensitive) /testFolder/test.PnG
on Windows using NTFS (which is not case sensitive) c:\testFolder\test.PnG
Now lets create some Java File Objects to each Image File.
// on Linux
File f1 = new File("/testFolder/test.png");
File f2 = new File("/testFolder/test.PNG");
File f3 = new File("/testFolder/test.PnG");
f1.exists(); // false
f2.exists(); // false
f3.exists(); // true
// on Windows
File f1 = new File("c:\\testFolder\\test.png");
File f2 = new File("c:\\testFolder\\test.PNG");
File f3 = new File("c:\\testFolder\\test.PnG");
f1.exists(); // true
f2.exists(); // true
f3.exists(); // true
Your problem is that all calls of File like File.exists are redirected to the java.io.FileSystem class that represents real Operating System calls of your File System by the JVM. So you cannot distinguish on Windows Machines between test.PNG and test.png. Neither do Windows itself.
But even on Windows each File has a defined name in the File System that could be for example: test.PnG. You will see this in your Windows Explorer or in Command Line if you type dir c:\testFolder.
So what you can do in Java is use the File.list method on the parent directory that results in the Operating System list call for all files in this directory with their real names.
File dir = new File("c://testFolder//");
for(String fileName : dir.list())
System.out.println(fileName);
// OUTPUT: test.PnG
or if you prefer File Objects
File dir = new File("c://testFolder//");
for(File file : dir.listFiles())
System.out.println(file.getName());
// OUTPUT: test.PnG
You can use this to write your own exists Method that is case sensitive on all operating systems
public boolean exists(File dir, String filename){
String[] files = dir.list();
for(String file : files)
if(file.equals(filename))
return true;
return false;
}
Use it like this:
File dir = new File("c:\\testFolder\\");
exists(dir, "test.png"); // false
exists(dir, "test.PNG"); // false
exists(dir, "test.PnG"); // true
EDIT: I have to admit that I was wrong. There is a way to get the real name of a File. I always overlooked the method File.getCanonicalPath.
Again our example: We have that File c:\testFolder\test.PnG.
File f = new File("c://testFolder//test.png");
System.out.println(f.getCanonicalPath());
// OUTPUT: C:\testFolder\test.PnG
With that knowledge you can write a simple test method for the case sensitive extension without iterating all files.
public boolean checkExtensionCaseSensitive(File _file, String _extension) throws IOException{
String canonicalPath = _file.getCanonicalPath();
String extension = "";
int i = canonicalPath.lastIndexOf('.');
if (i > 0) {
extension = canonicalPath.substring(i+1);
if(extension.equals(_extension))
return true;
}
return false;
}
Use it like this:
File f = new File("c://testFolder//test.png");
checkExtensionCaseSensitive(f, "png"); // false
checkExtensionCaseSensitive(f, "PNG"); // false
checkExtensionCaseSensitive(f, "PnG"); // true
If you are looking for a function that in any platform can determine existence of a file and is case-sensitive; this should do it :
public static boolean fileExistsCaseSensitive(String path) {
try {
File file = new File(path);
return file.exists() && file.getCanonicalFile().getName().equals(file.getName());
} catch (IOException e) {
return false;
}
}
I started messing around a little with this because I haven't used Apache's IOFileFilter before and thought that I would add this solution as a chance to play with it a little.
Here is the code:
import java.io.File;
import java.util.Collection;
import java.util.Optional;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
public class CaseInsensitiveFileFinder {
/**
* Attempts to find a file with the given <code>fileName</code> (irrespective of case) in the given
* <code>absoluteDirPath</code>. Note that while this method is able to find <code>fileName</code> ignoring case, it
* may not be able to do so if <code>absoluteDirPath</code> is in an incorrect case - that behavior is OS dependent.
*
* #param absoluteDirPath the absolute path of the parent directory of <code>fileName</code> (e.g. "/Users/me/foo")
* #param fileName the name of the file including extension that may or may not be the correct case
* (e.g. myfile.txt)
* #return an optional reference to the file if found, {#link Optional#empty()} will be returned if the file is not
* found
*/
public Optional<File> findFileIgnoreCase(String absoluteDirPath, final String fileName) {
File directory = new File(absoluteDirPath);
if (!directory.isDirectory()) {
throw new IllegalArgumentException("Directory '" + absoluteDirPath + "' isn't a directory.");
}
IOFileFilter caseInsensitiveFileNameFilter = new IOFileFilter() {
#Override
public boolean accept(File dir, String name) {
boolean isSameFile = fileName.equalsIgnoreCase(name);
return isSameFile;
}
#Override
public boolean accept(File file) {
String name = file.getName();
boolean isSameFile = fileName.equalsIgnoreCase(name);
return isSameFile;
}
};
Collection<File> foundFiles = FileUtils.listFiles(directory, caseInsensitiveFileNameFilter, null);
if (foundFiles == null || foundFiles.isEmpty()) {
return Optional.empty();
}
if (foundFiles.size() > 1) {
throw new IllegalStateException(
"More requirements needed to determine what to do with more than one file. Pick the closest match maybe?");
}
// else exactly one file
File foundFile = foundFiles.iterator().next();
return Optional.of(foundFile);
}
}
And here are some test cases:
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Optional;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.google.common.io.Files;
/**
* Non-quite-unit tests for {#link CaseInsensitiveFileFinder} class.
*/
public class CaseInsensitiveFileFinderTest {
private static String APPENDABLE_NEW_TMP_DIR_PATH;
/**
* Create the files with different cases.
* #throws IOException
*/
#BeforeClass
public static void setup() throws IOException {
File newTmpDir = Files.createTempDir();
String newTmpDirPath = newTmpDir.getCanonicalPath();
final String appendableNewTmpDirPath;
String fileSeparator = System.getProperty("file.separator");
if (!newTmpDirPath.endsWith(fileSeparator)) {
appendableNewTmpDirPath = newTmpDirPath + fileSeparator;
}
else {
appendableNewTmpDirPath = newTmpDirPath;
}
CaseInsensitiveFileFinderTest.APPENDABLE_NEW_TMP_DIR_PATH = appendableNewTmpDirPath;
File foofileDotPng = new File(appendableNewTmpDirPath + "FOOFILE.PNG");
Files.touch(foofileDotPng);
assertTrue(foofileDotPng.isFile());
File barfileDotJpg = new File(appendableNewTmpDirPath + "BARFILE.JPG");
Files.touch(barfileDotJpg);
assertTrue(barfileDotJpg.isFile());
}
#AfterClass
public static void teardown() throws IOException {
File newTmpDir = new File(CaseInsensitiveFileFinderTest.APPENDABLE_NEW_TMP_DIR_PATH);
assertTrue(newTmpDir.isDirectory());
// delete even though directory isn't empty
FileUtils.deleteDirectory(newTmpDir);
}
#Test
public void findFooFilePngUsingLowercase() throws IOException {
CaseInsensitiveFileFinder fileFinder = new CaseInsensitiveFileFinder();
Optional<File> optFoundFile = fileFinder.findFileIgnoreCase(APPENDABLE_NEW_TMP_DIR_PATH, "foofile.png");
assertTrue(optFoundFile.isPresent());
File foundFile = optFoundFile.get();
assertTrue(foundFile.isFile());
assertEquals(APPENDABLE_NEW_TMP_DIR_PATH + "FOOFILE.PNG", foundFile.getCanonicalPath());
}
#Test
public void findBarFileJpgUsingLowercase() throws IOException {
CaseInsensitiveFileFinder fileFinder = new CaseInsensitiveFileFinder();
Optional<File> optFoundFile = fileFinder.findFileIgnoreCase(APPENDABLE_NEW_TMP_DIR_PATH, "barfile.jpg");
assertTrue(optFoundFile.isPresent());
File foundFile = optFoundFile.get();
assertTrue(foundFile.isFile());
assertEquals(APPENDABLE_NEW_TMP_DIR_PATH + "BARFILE.JPG", foundFile.getCanonicalPath());
}
#Test
public void findFileThatDoesNotExist() {
CaseInsensitiveFileFinder fileFinder = new CaseInsensitiveFileFinder();
Optional<File> optFoundFile = fileFinder.findFileIgnoreCase(APPENDABLE_NEW_TMP_DIR_PATH, "dne.txt");
assertFalse(optFoundFile.isPresent());
}
#Test
public void findFooFileUsingDirWithNoTrailingFileSeparator() throws IOException {
CaseInsensitiveFileFinder fileFinder = new CaseInsensitiveFileFinder();
String newDirPathWithNoTrailingFileSep = StringUtils.chop(APPENDABLE_NEW_TMP_DIR_PATH);
Optional<File> optFoundFile = fileFinder.findFileIgnoreCase(newDirPathWithNoTrailingFileSep, "FOOFILE.PNG");
assertTrue(optFoundFile.isPresent());
File foundFile = optFoundFile.get();
assertTrue(foundFile.isFile());
assertEquals(APPENDABLE_NEW_TMP_DIR_PATH + "FOOFILE.PNG", foundFile.getCanonicalPath());
}
}
Hope that helps.
Instead of returning t (the file extension) return the file Object. That way your certain that you have the correct file. If you don't want to return the file object return the file name with the extension.
public static File getPhotoFileExtension(int empKey){
try{
String[] types = {".jpg",".JPG",".png", ".PNG"};
for(String t : types)
{
String path = "/"+Common.PHOTO_PATH + empKey + t;
File f = new File(Sessions.getCurrent().getWebApp()
.getRealPath(path));
if(f.isFile())
return f;
}
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
With that NiMa Thr said, you can do what you are looking for with this code :
On Windows, if the file exists, with any case, it will return true. If the file doesn't exists, the canonical name will be the same, so it will return false.
On Linux, if the file exists with a different case, the canonical name will return this different name, and the method will return true.
public static boolean fileExistsCaseInsensitive(String path) {
try {
File file = new File(path);
return file.exists() || !file.getCanonicalFile().getName().equals(file.getName());
} catch (IOException e) {
return false;
}
}

I want to create a class to create a file, and use main class to check if that file is created, but my code fail. (Java)

public class Fileverifynanoha
{
private File fileext;
private Path filepath;
public Fileverifynanoha()//this class wants to create a file, write something, and close it.
{
filepath = Paths.get("./txttest.txt");
Charset charset = Charset.forName("US-ASCII");
String s = "Takamachi Nanoha. Shirasaki Tsugumi.!";
try (BufferedWriter filewriter = Files.newBufferedWriter(filepath,charset))
{
filewriter.write(s,0,s.length()-1);
}
catch(IOException e)
{
System.err.println(e);
}
}//end of this class
/**
* #param args the command line arguments
*/
public static void main(String[] args)//the main method will check if this file contains(created), if so, return exist. if not, return doesnt exist.
{
if (filetxt.exists()&&!filetxt.isDirectory())//object does not create any real thing, therefore nothing true will return.
{
System.out.println("File exist.");
}
else
{
System.out.println("File does not exist.");
}
}
}
Here is the code. I want to use the class I create to create a file, write something. Then, I use main class to check if that file exist.
However, I don't know why, but the main class does not recognise my (maybe) created file. Could anyone tell me how to link them together?
I know there may be some minor bugs in this program. I will fix that later.
Thanks.
You never called your constructor.
public static void main(String[] args)//the main method will check if this file contains(created), if so, return exist. if not, return doesnt exist.
{
Fileverifynanoha fvn = new Fileverifynanoha();
if (fvn.filetxt.exists()&&!fvn.filetxt.isDirectory())
{
System.out.println("File exist.");
}
else
{
System.out.println("File does not exist.");
}
}
}
Your issues:
Didn't create instance of class.
Didn't init File file, so it would be null always.
Better use utf-8 for plain text file.
Try this:
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Fileverifynanoha {
private File file;
private Path path;
public Fileverifynanoha(String fp) {
this.path = Paths.get(fp);
this.file = path.toFile();
}
public void createFile()// this class wants to create a file, write something, and close it.
{
Charset charset = Charset.forName("UTF-8");
String s = "Takamachi Nanoha. Shirasaki Tsugumi.!";
BufferedWriter filewriter = null;
try {
filewriter = Files.newBufferedWriter(path, charset);
filewriter.write(s, 0, s.length() - 1);
filewriter.close();
} catch (IOException e) {
System.err.println(e);
}
}// end of this class
/**
* #param args
* the command line arguments
*/
public static void main(String[] args)// the main method will check if this file contains(created), if so, return exist. if not, return doesnt exist.
{
Fileverifynanoha f = new Fileverifynanoha("./txttest.txt");
f.createFile();
if (f.file.exists() && !f.file.isDirectory())// object does not create any real thing, therefore nothing true will return.
{
System.out.println("File exist.");
} else {
System.out.println("File does not exist.");
}
}
}

Program to get all files within a directory in Java

I'm working on this program to get all the files in the directory. For some reason I am getting a NullPointerException on Line 16. I don't know why though since this is a template that seemed to work in class with our teacher. Thanks.
import java.util.*;
import java.io.*;
public class FindDirectories {
public static void main(String[] args) {
if (args.length == 0) {
args = new String[] { ".." };
}
List<String> nextDir = new ArrayList<String>();
nextDir.add(args[0]); // either the one file, or the directory
try {
while(nextDir.size() > 0) { // size() is num of elements in List
File pathName = new File(nextDir.get(0)); // gets the element at the index of the List
String[] fileNames = pathName.list(); // lists all files in the directory
for(int i = 0; i < fileNames.length; i++) {
File f = new File(pathName.getPath(), fileNames[i]); // getPath converts abstract path to path in String,
// constructor creates new File object with fileName name
if (f.isDirectory()) {
System.out.println(f.getCanonicalPath());
nextDir.add(f.getPath());
}
else {
System.out.println(f);
}
}
nextDir.remove(0);
}
}
catch(IOException e) {
e.printStackTrace();
}
}
}
Check out the Javadoc for File.list(). Specifically:
Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.
In your code pathName.list(); must be returning null so pathName does not represent a valid directory, or an IO error occurred trying to get a list of files from that directory.
Use bellow snippet to get all the files from all the sub directories:
import java.io.File;
/**
*
* #author santoshk
*/
public class ListFiles {
File mainFolder = new File("F:\\personal");
public static void main(String[] args)
{
ListFiles lf = new ListFiles();
lf.getFiles(lf.mainFolder);
}
public void getFiles(File f){
File files[];
if(f.isFile())
System.out.println(f.getAbsolutePath());
else{
files = f.listFiles();
for (int i = 0; i < files.length; i++) {
getFiles(files[i]);
}
}
}
}
If you're getting a NullPointerException on line 16, it must mean that fileNames is null, so fileNames.length is invalid. Take a look at the javadoc for File.list and you'll see that pathName.list() can be null if pathName is not a directory, or if an exception occurs. So you'll just need to check whether fileNames is null before trying to use it.
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
public class FileEnumerator {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
// Prepare the List of files
String path = "C:/";
ArrayList<String> Files = new ArrayList<String>();
LinkedList<String> Dir = new LinkedList<String>();
File f = new File(path);
Dir.add(f.getAbsolutePath());
while(!Dir.isEmpty())
{
f = new File(Dir.pop());
if(f.isFile())
{
Files.add(f.getAbsolutePath());
}
else
{
String arr[] = f.list();
try
{
for(int i = 0;i<arr.length;i++)
{
Dir.add(f.getAbsolutePath()+"/"+arr[i]);
}
}
catch(NullPointerException exp)
{
Dir.remove(f.getAbsoluteFile());
}
}
}
//Print the files
for(int i = 0;i<Files.size();i++)
{
System.out.println(Files.get(i));
}
}
}
I think this code should work well. Although I have tested it just on Windows. But other OS will need at most small changes.
import java.io.*;
public class filedir
{
public static void main(String[] args)
{
try{
Files f = new File("C:\\");//the path required
String a[];
a=f.list();
for (int i = 0; i <a.length; i++) {
System.out.println(a[i]);
}
} catch(Exception e) {
System.err.println(e);
}
}
}

Categories

Resources