How to access directory with full file path? - java

So, I'm writing a program that needs to iterate through all files in a directory and here is what I currently have.
import java.io.File;
import java.util.Scanner;
public class Main {
public static void main(String args[]) throws Exception {
VotingData v = new VotingData();
Scanner in = new Scanner(System.in);
System.out.print("Please input a directory.");
String input = in.next();
File dir = new File(input);
File[] directoryListing = dir.listFiles();
if (directoryListing != null) {
for (File child : directoryListing) {
v.merge(RecordReader.readRecord(child.toString()));
}
}
else {
// do nothing right now.
}
String[] sub1 = {"Montgomery","Miami"};
TextualRepresentation.toString(v.getAllResults());
TextualRepresentation.toString(v.getCountyResults("Montgomery"));
TextualRepresentation.toString(v.getCountyResults("Miami"));
TextualRepresentation.toString(v.getCountyResults("Butler"));
TextualRepresentation.toString(v.getSubsetResults(sub1));
}
}
The filepath of the project is C:\Users\Jarrett Willoughby\Documents\School\CSE201\Project Stuff.
The input I'm trying is "C:\Users\Jarrett Willoughby\Documents\School\CSE201\Project Stuff\TestFiles" , but it doesn't seem to work. However, when input is just "TestFiles" it does. I want to be able to access directories in different folders, but for some reason the long method isn't working.
Edit: I don't know what the error is. All I know is when I put "TestFiles" into the Scanner it works fine and when I try the full file path it doesn't crash, but it doesn't yield the results I want.

Scanner#next() reads white-space delimited (by default) string tokens.
Your input:
C:\Users\Jarrett Willoughby\Documents\School\CSE201\Project Stuff\TestFiles
Contains spaces, so next() just reads "C:\Users\Jarrett".
You can use Scanner#nextLine() instead.
In the future, to debug on your own, either step through in a debugger to see what values variables have, or add print-outs to verify, e.g. this would have led you to a solution quickly:
System.out.println("input was " + input);

Related

FileNotFoundException for a file I know is in the directory

In the following program I am trying to read from the Hw1_1.java source code. I get a FileNotFoundException every time (probably for a good reason). I know the program isn't complete as I am just trying to stop getting the exception. I am at a loss.
If someone could point me in the right direction I would greatly appreciate it.
package hw1_1;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Hw1_1 {
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
System.out.println("Please enter the name of a java source code file");
String inputFileName = console.next();
String outputFileName = (inputFileName + ".txt");
try {
File inputFile = new File(inputFileName);
Scanner in = new Scanner(inputFile);
PrintWriter out = new PrintWriter(outputFileName);
while ( in .hasNextLine()) {
String line = console.nextLine();
out.println(line);
}
in .close();
out.close();
} catch (FileNotFoundException exception) {
System.out.println("File Not Found");
}
}
}
It's really a good idea - to first check the user directory of your java program. Once you know, you can easily debug the FileNotFoundException issue.
You can simply print the user directory from following code.
System.out.println(System.getProperty("user.dir")) ;
Using absolute path for the file is another way of solving problem, but that's a little irregular way of doing.
You need to be aware of path complexity in your code, especially if you are using IDE as IDE can have a different execution path
Based on your code, if the value inputFileName is just the file name (let's say log.txt) and the execution path is actually different, then your code will never find the path
The quickest and dirty solution to quickly prove this is to use the full absolute path as the value of inputFileName for example:
String inputFileName = "/var/tmp/log.txt"
or
String inputFileName = "C:/workspace/temp/log.txt"
Once this verifies that your code can read the file, then you can start handling the path issue, good luck.

reading txt file and writing a dictionary

My objective is to eventually make a spell checker but I need a dictionary of words to do that.
Here I'm trying to allow the user to input any number of text files as long as there's a space in between the file names ("novel1.txt novel2.txt novel3.txt").
I will use every word from these novels to write to a .dat file of individual words on individual lines(i.e. a dictionary of words). However I'm getting a file not found error at Scanner read = new Scanner(new File(filenames[i])); even though I know that I have the file.
I have even tried putting it in the source package to make sure it could be found.
At the very bottom of my code is a small test I ran (commenting out the other code first) and it does indeed print "war.txt isn't a file," even though I can clearly see that I have the txt file and have typed it correctly.
Can somebody tell me why java isn't seeing my txt file or maybe doesn't think it is a normal file?
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the file names exactly.");
String userInput = in.nextLine();
String[] filenames = userInput.split(" "); // turning user input string into a string array so I can look at each string individually
// takes each individual string from filenames and turns each one into the file
// that the string should represent then adds the file's contents to my dictionary
for(int i = 0; i < filenames.length; i++){
Scanner read = new Scanner(new File(filenames[i]));
String word = null;
while(read.hasNext()){
if(read.next().length() >= 2){
word = read.next();
// write word into myDict.dat
}
System.out.println(word);
}
}
File war = new File("war.txt");
if(!war.isFile()){
System.out.println(war + " isn't a file.");
}
}
I believe you do something in a wrong way. Try following example and compare it with your actual file locations.
Demo.java
import java.io.*;
class Demo {
public static void main(String[] args) throws IOException {
File war = new File("war.txt");
if(!war.isFile()){
System.out.println(war + " isn't a file.");
} else {
System.out.println(war + " is a file.");
}
}
}
compile and run it
javac Demo.java
java Demo
output
war.txt isn't a file.
now create in the same directory the war.txt
echo "foobar" > war.txt
run the code again
java Demo
output
war.txt is a file.
For the FileNotFoundException make sure that files are in your classpath if you insert only the filenames (for example if you use eclipse put the files on the root folder of the project).
For the war.txt issue you should do this:
File war = new File("war.txt");
if (!war.exists()) {
war.createNewFile();
}
if(!war.isFile()){
System.out.println(war + " isn't a file.");
}
This because when you do File war = new File("war.txt"); you are not creating the file, you have to explicitily create it with war.createNewFile();.
Finally, pay attention here:
if(read.next().length() >= 2){
word = read.next();
// write word into myDict.dat
}
System.out.println(word);
You do two times read.next() without check read.hasNext() the second time. You should write something like that:
while(read.hasNext()){
String next = read.next();
if(next.length() >= 2){
word = next;
// write word into myDict.dat
}
System.out.println(word);
}

How do I scan a folder so I can list the name of its contents in a text file? Java

Here is my code. So far I was able to get the directory they want to scan and the what they want to name the output file. The goal is to go to a folder and be able to scan all of that filder children names. Then I take the names and save them to a text file. I only get the names of the children of the specified folder. It is NOT supposed to open other folders and get there children. In my method listFilesForFolder(), I get a null pointer excpetion. Can someone help me figure out why i get the nullpointer exception? My code makes sense to me.
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
public class ReadWriteMain {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Scanner reader = new Scanner(System.in);
System.out.println("Please Enter the name of the output file... ");
String name = reader.nextLine();
System.out.println("Please Enter the file path of the directory you would like to copy... ");
String list = reader.nextLine();
final File folder = new File(list);
listFilesForFolder(folder, name);
}
public static void listFilesForFolder(final File folder, String name) throws IOException {
System.out.println("C:\\tempJava\\" + name + ".out");
FileWriter fw = new FileWriter("C:\\tempJava\\" + name + ".out");
PrintWriter output = new PrintWriter(fw);
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry, name);
} else {
output.println(fileEntry.getName());
}
}
output.close();
fw.close();
}
}
"It is NOT supposed to open other folders and get there children."
Then don't do this if (fileEntry.isDirectory()) { listFilesForFolder(fileEntry, name); ...
"In my method listFilesForFolder(), I get a null pointer excpetion."
If the folder you are trying to read does not exist, or you don't have permission to read it, listFiles() will return null. Gotta check for that.
I think your issue is in this line (not your other method):
final File folder = new File(list);
Given your code and a directory structure like this:
C:
tempJava
myFolder
Your input should be as follows:
Please Enter the name of the output file...
output
Please Enter the file path of the directory you would like to copy...
C:\tempJava\myFolder
I think you may have just entered "myFolder" instead of "C:\tempJava\myFolder"?

Java.IO.Filenotfoundexception error, Can't find a file that exists in C:

I am recently beginning programming and cannot get my program to find a file, then read input from it. Says the file does not exist. Here is my code.
import java.util.*;
import java.io.*;
public class assignment3 {
public static void main(String args[]) throws IOException {
PrintWriter pw = new PrintWriter("C:\\file\\Summary.txt");
Scanner k = new Scanner(System.in);
String filename;
System.out.println("--------------------------------\nBowsers Nuclear Weapons Inventory\n" +
"---------------------------------");
System.out.print("Please enter the name of the file: ");
filename = k.next();
File f = new File(filename);
System.out.println(f);
Scanner inputFile = new Scanner(f);
String Game1 = inputFile.nextLine();
System.out.println(Game1);
inputFile.close();
}
}
At line Scanner inputfile = new Scanner(f);. The error mentioned appears. Also when prompted to type in the file name in the program, i put "C:/Games.txt".....but when i got the filename to be printed out the filename is registerd as C:\Games.txt....why is the forward slash turning into a backslash. Thank you for taking the time to help me.
Make sure the folder named "file" exists (for creating a file). It might throw that error if it's not there. For reading you need to have the proper rights.
why is the forward slash turning into a backslash?
Because you're on Windows, and directories are natively separated by a \
Next, you don't appear to be writing with your PrintWriter. And if you want to check for a file that exists, call File#exists().
File f = new File(filename);
if (f.exists()) {
System.out.println(f);
Scanner inputFile = new Scanner(f);
while (inputFile.hasNextLine()) {
System.out.println(inputFile.nextLine());
}
} else {
System.out.println(f.getPath() + " does not exist");
}
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Answer {
public static void main(String args[]) throws IOException, FileNotFoundException {
// Have to throw a FileNotFoundException just in case an error occurs the compiler needs to know how to process the error.
PrintWriter pw = new PrintWriter("C:/file/Summary.txt");
Scanner k = new Scanner(System.in);
String filename;
System.out
.println("--------------------------------\nBowsers Nuclear Weapons Inventory\n"
+ "---------------------------------");
System.out.print("Please enter the name of the file: ");
filename = k.nextLine(); //Input for strings
System.out.println(filename);
File f = new File("C:/file/"+filename+".txt"); //Must have a location for your files
f.createNewFile(); //The file's pathname is the only thing that you can supply when you instantiate the object
//you actually have to invoke the createNewFile method upon the object.
if(f.exists()) { //Don't be afraid to check your code this is a must for every programmer.
System.out.println("Good! The File Exists");
}
Scanner inputFile = new Scanner(f);
String Game1 = inputFile.nextLine();
System.out.println(Game1);
inputFile.close();
}
}
When you create a file you always have to throw a FileNotFoundException if you do not the compiler will not know what to do if the error occurs. Use / when specifying directories of files.
\ is generally used as an escape sequence and when you type this \ \ your basically telling it to escape itself this code is useful in other situations but not this one.
You can NOT create a new file by the initiation of the object you always have to invoke the createNewFile method upon the object so that you can create a new file. This is because no constructors automatically call the createNewFile method in the class. You might be wondering what the words in the parameter are, they just serve the purpose of naming the file directory. I have found a helpful link if you want to review creating Files. Just look under the constructors tab. API Files Class
BE SURE! to always check your code, it does not matter how good of a programmer you are. You ALWAYS have to check for errors and if you make a game, and don't know where the error is among the millions of lines of code. You are going to have a hell of a time.
Lastly, I was not sure what you were trying to do after the if statement, but you will receive an error after the if statement, so if you want to ask me how to help with that just type in the comments of my post.

Why user.home returns "\" not "/"?

Maybe some of you will tell me where the mistake is, because I'm sitting on this for a few hours and didnt see anything.
The program should check if the if can be found in a txt file and return it to the bottom.
The second question about user.home
When I use it gets "C: \ Users \ Daniel / test / Test.java" by which the program does not work when I set the path to "C :/ Users / Daniel / test / Test.java" program begins to find my .txt file, but i cant leave it like that it must be found by user.home :(
public class Main {
public static void main(String ... args) throws Exception {
String usrHome = System.getProperty("user.home");
Finder finder = new Finder(usrHome + "/Testy/Test.java");
int nif = finder.getIfCount();
System.out.println("Number found 'if'": " + nif);
}
}
And finder class:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Finder {
String file;
Finder(String file){
file = this.file;
}
int getIfCount() throws FileNotFoundException{
int count = 0; String tmp; String lf = "if";
Scanner sc = new Scanner (new File("C:/Users/Daniel/Testy/Test.java"));
while(sc.hasNext()){
tmp = sc.next();
System.out.println(tmp); //to check if it works correctly
if(tmp == lf){
count++;
}
}
sc.close();
return count;
}
}
The result should look like this:
Number found "if": 3
Because there are three such elements, although the result is always 0
the result is always 0
Because you use == with String, try to Use equals() when you compare two string
if (tmp.equals(lf)) {
count++;
}
A better way to do the filename concatenation would be this:
File home = new File(System.getProperty("user.home"));
File file = new File(home, "Testy/Test.java");
/* Or even ...
File file = new File(new File(home, "Testy"), "Test.java");
*/
Finder finder = new Finder(file);
This avoids needing to know about the platform pathname representation.
The miscounting issue is caused by a basic Java 101 mistake. You are using '==' to compare Strings. It (usually) doesn't work. Use String.equals(...).

Categories

Resources