Need help creating a file in java - 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/

Related

createNewFile() Throws FileNotFoundException When Given the Correct FilePath

Here is my code below:
public void playerNaming() throws IOException {
Scanner pickName = new Scanner(System.in);
System.out.println("What do you want your username to be?");
String playerName = pickName.nextLine();
userName = playerName;
File file1 = new File("PlayerFiles\\" + playerName + ".txt");
File file2 = new File(file1.getAbsolutePath());
System.out.println(file2);
file2.createNewFile();
BufferedWriter file3 = new BufferedWriter(new FileWriter(file2));
}
On line file2.createNewFile(); It throws
java.io.FileNotFoundException: (Insert correct FilePath here) The system cannot find the path specified
What is wrong? According to all the articles and other stackoverflow questions I have read, this should work.
Check your file path :
public static void main(String args[])
{
try {
// Get the file
File f = new File("F:\\program1.txt");
// Create new file
// if it does not exist
if (f.createNewFile())
System.out.println("File created");
else
System.out.println("File already exists");
}
catch (Exception e) {
System.err.println(e);
}
Note : The file “F:\program.txt” is a existing file in F: Directory.

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...
}

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

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

Why the file is not created

I'm creating a directory and then a file. The problem is that the directory is created but the File is not.
When I'm doing this I'm creating and it prints out that "Successfully created new file: and the name of the file.
Can anyone help understand why?
public class Main
{
public static void main(String[] args) throws IOException
{
Scanner reader = new Scanner (System.in);
boolean success = false;
GetFiles getFile = new GetFiles();
System.out.println("Enter path of directory to create");
String dir = reader.nextLine();
// Create a new directory in Java, if it doesn't exists
File directory = new File(dir);
if(directory.exists())
{
System.out.println("Directory already exists");
}
else
{
System.out.println("Directory not exists, creating now");
success = directory.mkdir();
if(success)
System.out.println("Successfuly created new directory");
else
System.out.println("Failed to create new directory");
}
// Creatning new file in Java, only if not exists
System.out.println("Enter file name to be created");
String filename = reader.nextLine();
File f = new File(filename);
if(f.exists())
{
System.out.println("File already exists");
}
else
{
System.out.println("No such file exists, creating now");
success = f.createNewFile();
if(success)
System.out.printf("Successfully created new file: : %s%n", f);
else
System.out.printf("Failed to create new file: %s%n", f);
}
reader.close();
getFile.getAllFiles(directory);
}
}
Your code is completely working. It actually creates the file. You can see the created file in your java project.
Just add this line of code and it will work as you wish.
filename = dir + "\\" + filename;
File f = new File(filename);
I think the best ways --> to change the below lines:
#1.
if(directory.exists())
to below
if (directory.exists() && directory.isDirectory())
#2.
File f = new File(filename);
if(f.exists())
to below
File f = new File(directory,filename);
if (f.exists() && f.isFile()) {

How to capture the file name from the server dynamically when some one uploads it

Below is the code to read the file from the server. I Want to read & convert the file dynamically (not hard coded )into different file format(CSV). Could anyone please guide me to capture the uploaded file name dynamically.
try
{
//creating File instance to reference text file in Java
String str1=null;
String str2=null;
String str3=null;
int cnt=0,len1=0,len2=0;
File text = new File("C:\\Petty Ascii Detail.txt");
//Creating Scanner instnace to read File in Java
Scanner scnr = new Scanner(text);
File file = new File("C:\\Test\\Write1.txt");
//if file doesnt exists, then create it
if (!file.exists())
{
file.createNewFile();
}
//Reading each line of file using Scanner class
int lineNumber = 1;
while(scnr.hasNextLine())
{
String line = scnr.nextLine();
cnt=line.length();
for(int i=0;i<3;i++)
{
if (Character.isDigit(line.charAt(i)))
str1=line;
else
str2=line;
}
len1=str1.length();
len2=str2.length();
if(len1!=len2)
{
str3=str1+str2;
FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(str3);
bw.newLine();
System.out.println("Done");
bw.close();
}
lineNumber++;
}
}
catch (IOException e)
{
e.printStackTrace();
}
Any suggestions are really appreciated.
Thanks,
Balaji

Categories

Resources