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);
}
}
}
Related
So I have this code where it prompts the user to type in a file name for the input file and the file name for the output file. I have a string called 'names' which will then be stored into the input file that was created by the user. I've got this part down.
import com.sun.org.apache.xpath.internal.SourceTree;
import java.io.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
FileWriter writer = new FileWriter(chooseFile("input"));
FileWriter writer2 = new FileWriter(chooseFile("output"));
String separator = String.format("%n");
for(String name: names){
writer.write(name);
writer.write(separator);
}
}
}
public static File chooseFile(String type) {
String fname = null;
}
return file;
}
}
Something like so should modify your names list to all caps.
for (int i = 0; i < names.length; i++) {
names[i] = names[i].toUpperCase();
// writer2.write(names[i]);
}
How can I go to each subfolder in a given directory and take a pdf file from there like wise collect all pdf from all subfolders and move to a common folder?.
I've tried below code which is failing.
import java.io.File;
import java.io.IOException;`enter code here`
import java.nio.file.Files;
import java.util.ArrayList;
public class PDFMover{
/**
* #param args
* #return
* #throws IOException
*/
public static void main(String[] args) throws IOException {
File mainfolder = new File("C:\\Users\\myuser\\Desktop\\X\\Report");
File[] fulllist = mainfolder.listFiles();
ArrayList<String> listofpath = new ArrayList<String>(fulllist.length);
for (File x : fulllist)
{
if (x.isDirectory())
{
System.out.println("Directory:" +x.getName());
}
else
{
System.out.println("Notfound");
}
}
String source = "C:\\Users\\myuser\\Desktop\\X\\Report";
String destination ="C:\\Users\\myuser\\Desktop\\Destination";
File f1 = new File(source);
File f2 = new File(destination);
for (File x : fulllist)
{
if(mainfolder.isDirectory())
{
Files.copy(f1.toPath(), f2.toPath());
}
}
}
}
If you use nio.Files the solution to find every file in every subdirectory would be:
import java.nio.file.FileSystems;
import java.nio.file.Files;
public class FileWalker
{
public static final String PATH = "C:\\Users\\myuser\\Desktop\\X\\Report";
public static void main(final String[] args) throws Exception
{
Files.walk(FileSystems.getDefault()
.getPath((PATH)))
.map(path -> path.getFileName())
.filter(name -> name.toString()
.toLowerCase()
.endsWith("pdf"))
.forEach(System.out::println);
}
}
Instead of System.out.println you have to copy the files.
You can either use a recursive function, or use an explicit stack to do this. You simply check each of the files to see if they match your selection criteria. If not and if it's a directory you put it in the stack and move on.
Here's some working code using this approach. It let's you find files with a particular extension down to a particular recurs depth. The getRecurseFiles() returns a list of canonical path strings.
import java.util.*;
import java.io.*;
class Tracker {
File[] list;
int depth;
public Tracker (File[] l, int d) {
this.list = l;
this.depth = d;
}
}
public class RecTraverse {
public static int MAX_DEPTH = 10;
List<String> getRecurseFiles (String dir) throws IOException {
List<String> requiredFiles = new ArrayList<>();
Stack<Tracker> rstack = new Stack<>();
File[] list = new File(dir).listFiles();
rstack.push(new Tracker(list, 1));
while (!rstack.empty()) {
Tracker tmp = rstack.pop();
for (int i=0; i<tmp.list.length; i++) {
File thisEntry = tmp.list[i];
String fileName = tmp.list[i].getCanonicalPath();
if (thisEntry.isFile()) {
int j = fileName.lastIndexOf('.');
if (j > 0) {
String extension = fileName.substring(j+1).toLowerCase();
if (extension.equals("pdf"))
requiredFiles.add(tmp.list[i].getCanonicalPath());
}
} else {
System.out.println(thisEntry.getCanonicalPath());
File[] thisEntryList = thisEntry.listFiles();
if (thisEntryList != null && tmp.depth+1 <= MAX_DEPTH) {
rstack.push(new Tracker(thisEntryList, tmp.depth+1));
}
}
}
}
return requiredFiles;
}
public static void main (String[] arg) {
try {
List<String> l = new RecTraverse().getRecurseFiles(".");
for (String s : l)
System.out.println(s);
} catch (IOException e) {
}
}
}
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());
I am trying to store string of array in a text file and read it. But I can't get it working. I am getting NullPointerError.
Exception in thread "main" java.lang.NullPointerException
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at in.isuru.justconverter.FileDbTool.readFile(FileDbTool.java:41)
at in.isuru.justconverter.Test.main(Test.java:10)
Here's two classes.
package in.isuru.justconverter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.swing.JOptionPane;
public class FileDbTool {
File dataFile;
ArrayList<String> filePath;
public void checkFile(){
dataFile = new File("db.txt");
if(dataFile.exists()){
readFile();
}else{
try {
dataFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Coudn't Create New File!");
System.exit(1);
}
}
}
public void readFile(){
int len;
try{
char[] chr = new char[4096];
StringBuffer buffer = new StringBuffer();
FileReader reader = new FileReader(dataFile);
try {
while ((len = reader.read(chr)) > 0) {
buffer.append(chr, 0, len);
}
}finally {
reader.close();
}
System.out.println(buffer.toString());
StringTokenizer st = new StringTokenizer(buffer.toString(), ",");
while (st.hasMoreTokens()) {
String value = st.nextToken();
filePath = null;
filePath = new ArrayList<String>();
filePath.add(value);
}
}catch(IOException e){
JOptionPane.showMessageDialog(null, "Read Error");
}
}
public String[] getFilePathArray(){
readFile();
return filePath.toArray(new String[filePath.size()]);
}
public File[] getFiles(){
String[] paths = getFilePathArray();
ArrayList<File> files = new ArrayList<File>();
for(int i = 0; i < paths.length; i++){
File file = new File(paths[i]);
files.add(file);
}
return files.toArray(new File[files.size()]);
}
public void eraseFile(){
dataFile.delete();
}
public void writeFile(String[] stuff){
try{
BufferedWriter out = new BufferedWriter(new FileWriter(dataFile, true));
out.append(stuff + ",");
}catch(IOException e){
}
}
public void writeToDb(String[] array){
writeFile(array);
}
}
And main class
package in.isuru.justconverter;
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
FileDbTool app = new FileDbTool();
app.checkFile();
}
}
Well this is a portion of a swing program. I am trying to use text file as a small database.
Line 41 is this:
FileReader reader = new FileReader(dataFile);
so I'd wager that dataFile is null here.
However, you do seem to initialize it before calling this method, otherwise the exception would be thrown inside checkFile.
Are you sure you are not calling readFile directly somewhere without calling checkFile first? In any case, this pattern is not a recommended approach, because you are requiring the users of your class to call methods in a specific order.
From the stack trace , it seems like you called readfile() directly from main rather than through checkfile() . So dataFile is null since it is not initialized by checkfile . Also the stack trace and the given code doesn't match . When FileReader constructor is called with null argument , it will throw NullPointerException when it reaches FileInputstream constructor .
Here is the code from jdk source :
public FileInputStream(File file) throws FileNotFoundException {
String name = (file != null ? file.getPath() : null);
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkRead(name);
}
if (name == null) {
throw new NullPointerException();
}
fd = new FileDescriptor();
fd.incrementAndGetUseCount();
open(name);
}
I want to copy the directory structure without copying the content/files. I want to copy only folder structure.
I have written a sample program but it is also copying the content/files also.
import java.io.*;
import java.nio.channels.*;
#SuppressWarnings("unused")
public class CopyDirectory{
public static void main(String[] args) throws IOException{
CopyDirectory cd = new CopyDirectory();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String source = "C:\\abcd\\Documents\\1";
File src = new File(source);
String destination = "C:\\abcd\\Documents\\2";
File dst = new File(destination);
cd.copyDirectory(src, dst);
}
public void copyDirectory(File srcPath, File dstPath) throws IOException{
if (srcPath.isDirectory())
{
if (!dstPath.exists())
{
dstPath.mkdir();
}
String files[] = srcPath.list();
for(int i = 0; i < files.length; i++)
{
System.out.println("\n"+files[i]);
copyDirectory(new File(srcPath, files[i]), new File(dstPath, files[i]));
}
}
System.out.println("Directory copied.");
}
}
I am struck at this point.
Thank you.
This worked for me:
import java.io.File;
public class StartCloneFolderOnly {
/**
* #param args
*/
public static void main(String[] args) {
cloneFolder("C:/source",
"C:/target");
}
public static void cloneFolder(String source, String target) {
File targetFile = new File(target);
if (!targetFile.exists()) {
targetFile.mkdir();
}
for (File f : new File(source).listFiles()) {
if (f.isDirectory()) {
String append = "/" + f.getName();
System.out.println("Creating '" + target + append + "': "
+ new File(target + append).mkdir());
cloneFolder(source + append, target + append);
}
}
}
}
So if I'm right, you just want to copy the folders.
1.) Copy directory with sub-directories and files
2.) Place 1. wherever
3a.) Instantiate to list files in parent directory into an arrayList
3b.) Instantiate to list the new subfolders into an arrayList
3c.) Instantiate to list all files in each subfolder into their own arrayLists
4.) Use a for-loop to now delete every file within the new directory and subfolder
From this, you should have a copy of the new directory with all files removed.
import java.io.*;
import java.nio.channels.*;
#SuppressWarnings("unused")
public class CopyDirectory{
public static void main(String[] args) throws IOException{
CopyDirectory cd = new CopyDirectory();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String source = "C:\\abcd\\Documents\\1";
File src = new File(source);
String destination = "C:\\abcd\\Documents\\2";
File dst = new File(destination);
cd.copyDirectory(src, dst);
}
public void copyDirectory(File srcPath, File dstPath) throws IOException{
if (srcPath.isDirectory())
{
if (!dstPath.exists())
{
dstPath.mkdir();
}
String files[] = srcPath.list();
for(int i = 0; i < files.length; i++)
{
System.out.println("\n"+files[i]);
copyDirectory(new File(srcPath, files[i]), new File(dstPath, files[i]));
}
}
System.out.println("Directory copied.");
}
}