Reading From directories+sub-directories - java

this is a semi homework and I've been trying for ages but without luck,basically I'm doing a Search engine-Like program,where i read files in my directory + their sub directory's and Read the text files to search for a match,i searched endlessly but without clear answer so I'd appreciate if any one could help.
this was my best try but the problem with it that it only took the files from the sub directory and ignored the main/root directory,tried to figure out why but couldn't.
public void indexDirectory(File dir) {
for(int i=0;i<50;i++)
ls[i]=new LinkList();//array of Linked lists to store addresses of each Linked list that has a file
try{
files= dir.listFiles();
for (int i = 0; i < files.length; i++) {
if(files[i].isDirectory())
indexDirectory(files[i]);
if(files[i].isFile()){
if(files[i]!=null)
indexFile(files[i]);
} //end if(isFile)
} //end For loop
}catch(FileNotFoundException e){
System.out.println("error ");
}}
second version after serching the web and trying to emulate what i found,but didn't work sadly.
public void indexDirectory(File dir) {
for(int i=0;i<50;i++)
ls[i]=new LinkList();
try{
if(dir.isFile()){
indexFile(dir); //this method takes each directory and read the words and save them in
// array of linked list
}
else if(dir.isDirectory()){
files= dir.listFiles();
if(files!=null) {
for (int i = 0; i < files.length; i++) {
if(files[i].isDirectory()){
indexDirectory(files[i]); //recursive call
}}
}catch(FileNotFoundException e){
System.out.println("error ");
}}

In the first version, you loop through the entire file.length and check only for file.isDirectory and after that (ie. after all files/folders have been traversed) you check if it is a file. That's why you cannot read through current directory's files. Simply put the
if(files[i].isFile()){
if(files[i]!=null)
indexFile(files[i]); //the method to read from these files and save to array of lists.
}
block in for loop and it should work in the first version.
One more thing I didn't understand the purpose of ls variable here.

Related

Save a File on a specific path

i have the current code:
public void crearArchivo(String nombre) {
archivo = new File(nombre.replaceAll("\\s", "") + ".txt");
if (!archivo.exists()) {
try {
archivo.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void crearCarpeta(String nombreCarpeta){
File directorio = new File(nombreCarpeta);
directorio.mkdir();
}
public void crearArchivoDatos(String nombreArchivo, ArrayList<String>datos) {
crearArchivo(nombreArchivo);
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(archivo));
for (int i = 0; i < datos.size(); i++) {
bw.write(datos.get(i));
}
bw.close();
} catch (Exception e) {
//e.printStackTrace();
}
}
the first method create a file only if it doesnt exist and the second one create a folder finally the third method save the data my problem is that i want to save some files on the folder i created first how can i set a path to save those file there, also i have the problem that this little program will execute at diferent computers so the path will change for any computer
You can get paths of folders on any computer using System.getProperty(...) - for example System.getProperty("user.home") gives you the current user directory (from which you can get to the desktop and other folders), and System.getProperty("user.dir") gives you the path of the folder from which your program is executed.
Creating or modifying files in Java can be done with the Java 8 NIO.2 methods.
Here is a link to the Oracle documentation : https://docs.oracle.com/javase/tutorial/essential/io/fileio.html
For your question, you have to declare a relative path, so it will be independent of the computer it will be executed on, rather than an absolute path, which begin on the root of the filesystem.

Recursing through a directory in java, I want to skip a step on the top level

I am trying to output a list of files within a directory recursively (not including the name of the name of the directory that I am starting with (just the contents of it and all files recursing down the tree after that)
here is what I have at the minute. It Might have errors here and there, but the idea is that it will print all the names of every file in the tree recursively. My problem is that I don't want it to print the name of the directory in which they live.
I think my problem is that I am using System.out.println at the start of the recursive method, which means it gets used every time. Which is desirable behavior for every directory BELOW the first one. Its an annoying little problem that I could use some help on. Thanks in advance.
public static void listFiles(String path)
{
File basedir = new File(path);
System.out.println(path.getName());
try
{
File[] files = basedir.listFiles();
for (File file : files)
{
// If Dealing with a directory, call recursively to the function
if (file.isDirectory())
{
listFiles(file.getPath());
}
else
{
System.out.println(file.getName());
}
}
}
catch(IOException ex)
{
System.out.println(ex);
}
}
public static void listFiles(String path, boolean firstCall)
{
File basedir = new File(path);
if(!firstCall)
{
System.out.println(path.getName());
}
try
{
File[] files = basedir.listFiles();
for (File file : files)
{
// If Dealing with a directory, call recursively to the function
if (file.isDirectory())
{
listFiles(file.getPath(), false); //false here because it is not the first call
}
else
{
System.out.println(file.getName());
}
}
}
catch(IOException ex)
{
System.out.println(ex);
}
}
Add a boolean parameter that specifies if it is the first call. When you call the method pass true to the parameter. Also path.getName() is not valid String doesn't have a function getName() maybe you meant basedir.getName()...also remove try catch block IOException can't occur there.

Using PrintWriter for file IO

Ok so I'm about to start pulling my hair out. I thought file input was a little tricky, but oh man then there is file output. I am trying to write an array of coordinates stored in an object to a file. In C++ this was easy peasy, but for the love of God I cannot figure this out.
public static void outFile(int intersectionsIndex, Coordinate arg[], Coordinate avgPoint) {
File file = new File("resource/result.txt");
file.getParentFile().mkdirs();
PrintWriter writer = new PrintWriter(file);
int i = 0;
while (i < intersectionsIndex) {
writer.print(arg[i].getX());
writer.print(" ");
writer.println(arg[i].getY());
i++;
}
writer.print("Predicted Coordinate: ");
writer.print(avgPoint.getX());
writer.print(" ");
writer.println(avgPoint.getY());
writer.close();
return;
}
I am constantly getting the same error no matter what method of IO I use. I followed some posts on here with similar problems but to no avail. Any suggestions or other methods? I am probably missing something basic.
Edit: sorry error is
Error:(83, 30) java: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
Which is the "PrintWriter writer = newPrintWriter(file); line.
UPDATE: Problem solved. Working code below:
public static void outFile(int intersectionsIndex, Coordinate arg[], Coordinate avgPoint) throws Exception{
File file = new File("resource/result.txt");
file.getParentFile().mkdirs();
PrintWriter writer = new PrintWriter(file);
int i = 0;
while (i < intersectionsIndex) {
writer.print(arg[i].getX());
writer.print(" ");
writer.println(arg[i].getY());
i++;
}
writer.print("Predicted Coordinate: ");
writer.print(avgPoint.getX());
writer.print(" ");
writer.println(avgPoint.getY());
writer.close();
return;
}
It looks like the error that you get is actually a compile-time error, not a runtime error.
The contructor PrintWriter(File) declares a checked FileNotFoundException in its signature, therefore you either need to surround its invocation with try ... catch block, or to declare that exception in throws declaration of your method to catch it later.
See also:
Lesson: Exceptions
Always try to avoid absolute path because the same code might not work on another system.
I suggest you to place it inside the project under resources folder.
You can try any one based on file location.
// Read from resources folder parallel to src in your project
File file1 = new File("resources/results.txt");
// Read from src/resources folder
File file2 = new File(getClass().getResource("/resources/results.txt").toURI());
You might forget to increment i in while loop. Add i++ to avoid infinite loop.
Try
while (i++ < intersectionsIndex) {...}
OR
while (i < intersectionsIndex) {
...
i++;
}

Java: checking if a file is present

Can somebody help me with this scenario?
I have a method which when run generates a number of files. The files can take anywhere from a couple of seconds to a minute to be generated so instead of just waiting for 2 minutes everytime I am trying to look at the number of files in the folder then check every second up to 2 minutes for the file count to go up.
If the file count doesn't go up in that 2 minutes I just want to carry on with the rest of the method instead of throwing an exception and exiting.
The problem is the first time it runs when it gets to new File(generatedFilesFolder).listFiles().length; it throws a null pointer exception because the generatedFilesFolder is empty at this point.
I could do this check after the generate.next() but then I would have to sleep which would defeat the point of what I am trying to archive.
Please can anyone tell me a better way? I tried changing the int to an Integer instead but it still threw an exception.
int actualFilesGenerated = new File(generatedFilesFolder).listFiles().length;
generate.next();
// / Now I want to give each file 2 minutes to generate otherwise catch and
// carry on with rest of method.
try {
int currentFilesGenerated = new File(generatedFilesFolder).listFiles().length;
int counter = 0;
while ((currentFilesGenerated < actualFilesGenerated) & counter < 120) {
Thread.sleep(1000);
currentFilesGenerated = new File(generatedFilesFolder).listFiles().length;
counter++;
System.out.println("actualFilesGenerated: " + actualFilesGenerated
+ " currentFilesGenerated: " + currentFilesGenerated + "counter: "
+ counter);
}
} catch (InterruptedException e1) {
e1.printStackTrace();
}
///rest of method here
You can use File.exists() to check the existence of a File
File f = new File(generatedFilesFolder)
if(f.exists()) {
// file exists and do the operation
}
else {
f.createNewFile(); //or f.mkdir() to create directory
}
The problem is the first time it runs when it gets to new File(generatedFilesFolder).listFiles().length; it throws a null pointer exception because the generatedFilesFolder is empty at this point.
This cannot be true. If generatedFilesFolder is effectively a path to a directory but there are no files in it, this will not throw an NPE but will return an empty array.
Therefore you need to generate your directory before going any further:
final File file = new File(generatedFilesFolder);
if (file.exists()) {
if (!file.isDirectory())
throw new IllegalStateException("not a directory");
} else {
if (!files.mkdirs())
throw new IllegalStateException("cannot create directory");
}
// go on
Finally: if you use Java 7, forget about File. Use Files. Which has a directory watcher...
you can use exists() method of File class to check if that file is present,
e.g.
File f=new File(path);
if(f.exists()) {
.....
}
there is exist method. So check if derectory exist before you get list of files
make a check before using it like.
File file = new File(generatedFilesFolder);
if(file.exists() && file.isDirectory()) {
// do something
}

How do I add data from a file to a JTable?

Here is my method so far:
public void readfile(JTable table) {
try{
BufferedReader in = new BufferedReader( new FileReader("out.txt"));
for(int i = 0; i<10; i++) {
for(int j = 0; j<5; j++) {
table.setValueAt(in.readLine(), i, j);
}
}
in.close();
}catch (Exception e) {
System.err.println("error: " + e.getMessage());
}
}
Here are the contents of out.txt:
test1
test2
test3
test4
test5
Where I run the program and attempt to load the file to the table, nothing happens. I also get an output that says the following:
error: 0 >= 0
Help me please?
I would narrow your problem down to a smaller problem, solve this smaller problem, and then widen it until you have want you want.
Think of the contents of a File as a big blob of text.
Think of the table as a Vector of Vectors.
Smaller problem: How do I convert a big blob of text into a Vector of Vectors? You need to be able to sove this problem first before tackling File I/O or DefaultTableModels.

Categories

Resources