User enters what the file name is they want to read in? - java

For the purpose of this class task, we have been asked to make a program that uses the File Class(I know input stream is much better) but yeah, we have to ask the user to input the name of the .txt file.
public class input {
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(System.in);
String name;
int lineCount = 0;
int wordCount = 0;
System.out.println("Please type the file you want to read in: ");
name = s.next();
File input = new File("C:\\Users\\Ceri\\workspace1\\inputoutput\\src\\inputoutput\\lab1task3.txt");
Scanner in = new Scanner(input);
How would I get
File input = new File(...);
to search for the file as just typing 'lab1task3' doesn't work.
edit: error -
Exception in thread "main" java.io.FileNotFoundException: \lab1task3.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at inputoutput.input.main(input.java:19)

Scanner can't read in files that way, you need to store it as a file first!
If you put this inside of a try-catch block, you can ensure that the program won't break if a file isn't found. I would suggest wrapping it in a do-while/while loop (depending on structure), with the end condition being that the file is found.
I changed your main method to this and it compiles correctly:
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner (System.in);
System.out.println("Please type the file you want to read in: ");
String fname = sc.nextLine();
File file = new File (fname);
sc.close();
}

To search for a file inside a specific folder, you could just iterate over the files inside the given folder via:
File givenFolder = new File(...);
String fileName = (...);
File toSearch = findFile(givenFolder, fileName);
Where the function findFile(File folder, String fileName) would iterate over the files in the givenFolder and try to find the file. It could look like this:
public File findFile(File givenFolder, String fileName)
{
List<File> files = getFiles();
for(File f : files)
{
if(f.getName().equals(fileName))
{
return f;
}
}
return null;
}
The function getFiles is just iterating over all files in the given folder and calls it self when finding a folder:
public List<File> getFiles(File givenFolder)
{
List<File> files = new ArrayList<File>();
for(File f : givenFolder.listFiles())
{
if(f.isDirectory())
{
files.addAll(getFiles(f));
}
else
{
files.add(f);
}
}
}
I hope this helps you :) If you want to know more about what happens here exactly feel free to ask :)

Related

Need help creating a file in java

I need a file to be created but one is not being created and I have no clue where it has gone wrong
This is where I have the text for the file name created
public class LetterGradeDisplayer {
public static void main(String[] args) {
LetterGradeConverter conv1 = new LetterGradeConverter("c://temp//grade1.txt", 6);
System.out.println("Contents: ");
System.out.println(conv1);
LetterGradeConverter conv2 = new LetterGradeConverter("c://temp//grade2.txt", 6);
System.out.println("Contents: ");
System.out.println(conv2);
This is where the argument for the file name is taken
public LetterGradeConverter(String fileName, int maxGrade) {
File file = new File(fileName);
int Grade[] = new int [maxGrade];
actualLength = maxGrade;
char LetterGradeList[] = new char [maxGrade];
int count = 0;
Scanner scan;
try {
scan = new Scanner(file);
while(scan.hasNextInt()) {
Grade[count] = scan.nextInt();
count++;
}
scan.close();
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
GradeConverter();
This is the error text I am getting:
java.io.FileNotFoundException: c:\temp\grade1.txt (The system cannot find the file specified)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(Unknown Source)
at java.base/java.io.FileInputStream.<init>(Unknown Source)
at java.base/java.util.Scanner.<init>(Unknown Source)
at LetterGrade.LetterGradeConverter.<init>(LetterGradeConverter.java:21)
at LetterGrade.LetterGradeDisplayer.main(LetterGradeDisplayer.java:7)
Exception in thread "main" java.lang.NullPointerException
at LetterGrade.LetterGradeConverter.GradeConverter(LetterGradeConverter.java:36)
at LetterGrade.LetterGradeConverter.<init>(LetterGradeConverter.java:32)
at LetterGrade.LetterGradeDisplayer.main(LetterGradeDisplayer.java:7)
You mention a file not being created, but I see nothing in your code that SHOULD create a file.
Are you expecting new File() to create the file on the filesystem for you? Because it won't, for that you need File#createNewFile
File file = new File("c://temp//testFile1.txt");
//Create the file
if (file.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}
//Write Content
FileWriter writer = new FileWriter(file);
writer.write("Test data");
writer.close();
"Use File.createNewFile() method to create a file. This method returns a boolean value : true if the file is created successfully; false if the file is already exists or the operation failed for some reason." - https://howtodoinjava.com/core-java/io/how-to-create-a-new-file-in-java/

FileReader won't read second file in a list

I put two files in a directory and tested to see if my code can search through the files and find a match, but the FileReader won't read the second file. Here is my code and my console entry. I have narrowed the error down to the FileReader, but I don't know how to fix that.
public class Main
{
public static void searchEngine(String dir, String Search)
{
File folder = new File(dir);
String[] files = folder.list();
Integer f1 = 0;
FileReader fileReader;
ArrayList linematches;
BufferedReader bufferedReader;
Integer q;
String line;
Integer linenum;
System.out.println("Found Files:");
for (String file : files) {
System.out.println(file);
}
try {
for (String file : files) {
linematches = new ArrayList();
fileReader = new FileReader(files[f1]);
bufferedReader = new BufferedReader(fileReader);
linenum = 0;
while ((line = bufferedReader.readLine()) != null) {
linenum += 1;
if (line.contains(Search)) {
linematches.add(linenum);
}
}
q = 0;
for (int i = 0; i < linematches.size(); i++) {
System.out.println("File: " + file + " Line: " + linematches.get(i));
}
linematches.removeAll(linematches);
// Always close files.
bufferedReader.close();
f1++;
}
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '" + dir + "'");
} catch (IOException ex) {
System.out.println("Error reading file '" + dir + "'");
}
}
public static void main(String[] args)
{
while (true) {
System.out.println("Enter the search term: ");
Scanner scanner = new Scanner(System.in);
String searchterm = scanner.nextLine();
System.out.println("Enter each file location: ");
String f1 = scanner.nextLine();
searchEngine(f1, searchterm);
}
}
}
Here is the output of my console:
Enter the search term:
bla
Enter each file location:
test dir
Found Files:
testfile.txt
testfile2.txt
Unable to open file 'test dir'
The entire stack trace of the error is:
Unable to open file 'testfile2.txt' java.io.FileNotFoundException:
testfile2.txt (No such file or directory) Enter the search term: at
java.io.FileInputStream.open0(Native Method) at
java.io.FileInputStream.open(FileInputStream.java:195) at
java.io.FileInputStream.(FileInputStream.java:138) at
java.io.FileInputStream.(FileInputStream.java:93) at
java.io.FileReader.(FileReader.java:58) at
com.mangodev.Main.searchEngine(Main.java:32) at
com.mangodev.Main.main(Main.java:70)
Please help. Thank you.
It looks to me as if you have the following folder structure:
Main.class
Main.java
test dir
|-- testfile.txt
|-- testfile2.txt
You run the code from the directory containing Main.class, Main.java and test dir. Your code then lists files in the directory test dir, finding the two text files it contains, but then attempts to open them from the current directory. This is the parent directory, and of course, this isn't where those files are. They are in the sub-directory test dir. A FileNotFoundException is therefore to be expected: you're attempting to open a file in the wrong directory.
If the FileReader happens to fail on the second of the two files, does there happen to be a file testfile.txt in the parent directory as well? Your code may well have been opening this file first time through the loop instead of the one in test dir that you thought it was.
To open files within the test dir subdirectory, replace the line
fileReader = new FileReader(files[f1]);
with
fileReader = new FileReader(new File(dir, files[f1]));
In your first line in the searchEngine method you create a variable folder that contains the files in the directory. I suggest using this variable directly in your for loop instead of string filenames.
for (File file : folder.listFiles()) {
linematches = new ArrayList();
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
//rest of code...
}

How to access directory with full file path?

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);

Java Check Vaild File

Please help, I need help on how to check for valid file names.
Here is part of my program...
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class BookstoreInventory
{
public static void main(String[] args)throws IOException
{
//Vaiable declartions
int edition, quanity;
double pricePerBook;
String isbn, author, title, publisherCode;
int totalQuant = 0;
double total = 0;
double totalValue = 0;
double sumOfPriceBook = 0;
//Scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
//Get the file name from the user
System.out.print("Enter the name of the file: ");
String filename = keyboard.nextLine();
//Open the file and set delimiters
File file = new File(filename);
Scanner inputFile = new Scanner(file);
inputFile.useDelimiter("_|/|\\r?\\n");
}
}
So in my program I'm not sure how I would check to see if it's a valid file. For example, when the user enters "inventory" for the name of the file this will produce an error because the filename needs the .txt so the user should have entered "inventory.txt". So is there a way to adding the .txt to the name they entered? Or how do I check to see if a file is valid? Any help would be much appreciated.
You can try this:
if (!fileName.trim().toLowerCase().endsWith(".txt")) {
fileName+= ".txt";
}
Also, if you want to know if the file already exists or not:
File file = new File(filename);
// If file doesn't exist then close application...
if (!file.exists()) { System.exist(0); }
Hope this helps.
Try concatenating the user's input string by adding .txt. It should work.

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"?

Categories

Resources