createNewFile() Throws FileNotFoundException When Given the Correct FilePath - java

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.

Related

Java functions delete() and renameTo() not deleting nor renaming

public void newEditSportRecord(){
String filepath = "sport.txt"; //exists in C:\Users\Dell\Documents\NetBeansProjects\Assignment\
String editTerm = JOptionPane.showInputDialog("Enter ID of Sport you wish to modify:");
String tempFile = "temp.txt"; // to be created in C:\Users\Dell\Documents\NetBeansProjects\Assignment\
File oldFile = new File(filepath);
System.out.println(oldFile.getAbsolutePath()); // prints C:\Users\Dell\Documents\NetBeansProjects\Assignment\sport.txt
File newFile = new File(tempFile);
System.out.println(newFile.getAbsolutePath()); // prints C:\Users\Dell\Documents\NetBeansProjects\Assignment\temp.txt
String ID, name = "";
try {
FileWriter fw = new FileWriter(tempFile, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
x = new Scanner(new File(filepath));
while (x.hasNextLine()) {
ID = x.next();
System.out.println(ID);
name = x.next();
System.out.println(name);
if (ID.equals(editTerm)) {
newID = JOptionPane.showInputDialog("Enter new Sport ID:");
newName = JOptionPane.showInputDialog("Enter new Sport Name:");
pw.println(newID);
pw.println(newName);
pw.println();
JOptionPane.showMessageDialog(modifySport, "Record Modified");
} else {
pw.println(ID);
pw.println(name);
pw.println();
}
}
x.close();
pw.flush();
pw.close();
oldFile.delete();
File dump = new File(filepath);
newFile.renameTo(dump);
} catch (Exception ex) {
JOptionPane.showMessageDialog(modifySport, ex);
}
}
I have the following function to try and modify a text file. However, it does NOT delete the original file "sport.txt" nor does it rename "temp.txt" to "sport.txt". It DOES read from the file and create a copy of "sport.txt" with all the relevant modifications as "temp.txt". I had suspected it was a problem with the writers but having closed all of them, the issue still persists. Is this simply down to permission problems as the folder exists in the Documents folder on Local Disk?
Yes, it is a permission problem. Either change the permission of the Documents folder and give access to all the permissions to your user or change your working folder.

check if the word in the set equals word in outside file

I have a set of words and an outside file.
I want to check if a word in the set is already present in the outside file. If the word is already in the file, then do nothing, if the word is not in the outside file already, then add it to the outside file.
This is the code I have written:
public static void toFile(Set<String> vocab, String filename)
{
try
{
for(String vocabWord : vocab)
{
File file = new File(filename);
Scanner sc2 = new Scanner(file);
while(sc2.hasNextLine())
{
String docWord = sc2.nextLine();
if (!(vocabWord.equals(docWord)))
{
FileWriter myWriter = new FileWriter(filename, true);
PrintWriter printWriter = new PrintWriter(myWriter);
printWriter.println(vocabWord);
printWriter.close();
}
else
break;
}
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
I am using three different text documents to test it, have the line "test file one", "test file two", and "test file three".
The output I was expecting was: "test file three" (it is connected with a stop list which one and two are part of, and has been working)
However, when I run it, either with only one of the files or all three consecutively, the file always comes out empty.
I tried changing up things in the method, but nothing has worked, I either get an infinite loop or nothing in the outside file.
I am not sure what I am missing... I would really appreciate any help.
I tried this and added some comments for explanation. I have tested on local machine and it works
public static void toFile(Set<String> vocab, String filename) {
try {
for(String vocabWord : vocab) {
//task for each String in our Set
File file = new File(filename);
Scanner sc2 = new Scanner(file);
boolean exists = false;//lets say it doesn't exist
while(sc2.hasNextLine()) {
//task for each line in the text
//search the whole file first for the word
String docWord = sc2.nextLine();
if (docWord.equals(vocabWord)){
exists = true;
break;
}
}
if (!exists) {
//add the vocabWord only if it doesnt exists
FileWriter myWriter = new FileWriter(filename, true);
PrintWriter printWriter = new PrintWriter(myWriter);
printWriter.println(vocabWord);
printWriter.close();
}
}
} catch(IOException e) {
e.printStackTrace();
}
}
To append the missing vocabulary in order of vocab, you can reduce the file operations
as such:
public static void toFile(Set<String> vocab, String filename) {
try {
Charset charset = Charset.defaultCharset();
Path path = Paths.get(filename);
Set<String> existing = Files.lines(path, charset)
.collect(Collectors.toSet());
if (!existing.isEmpty()) {
try (BufferedWriter bw = Files.newBufferedWriter(path, charset,
StandardOpenOption.APPEND);
PrintWriter printWriter = new PrintWriter(bw)) {
vocab.stream()
.filter(word -> !existing.contains(word))
.forEach(word -> printWriter.println(word));
}
}
} catch (IOException e) {
e.printStackTrace();
}
}

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/

Is this correctly writing to a text file?

I am trying to save the integers in an array to a text file. Neither of these seem to be doing the trick while sitting in my main method and I was wondering if someone could point out my mistake.
public static void main (String[] params) throws IOException
{
numberPlayers();
int diceroll = dicethrow(6);
int[] scorep1 = scorearrayp1();
questions(diceroll, scorep1);
sort(scorep1);
File file = new File ("C:/Users/Usman/Desktop/directory/scores.txt");
PrintWriter writer = new PrintWriter("scores.txt");
writer.println("Player 1 score: " + scorep1[0]);
writer.println("Player 2 score: " + scorep1[1]);
writer.println("Player 3 score: " + scorep1[2]);
writer.println("Player 4 score: " + scorep1[3]);
writer.close();
System.exit(0);
}
No score.txt file is created on my desktop in either of these attempts.
public static void main (String[] params) throws IOException
{
numberPlayers();
int diceroll = dicethrow(6);
int[] scorep1 = scorearrayp1();
questions(diceroll, scorep1);
sort(scorep1);
File file = new File("C:/Users/Me/Desktop/file.txt");
PrintWriter printWriter = null;
try
{
printWriter = new PrintWriter(file);
printWriter.println("hello");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
if ( printWriter != null )
{
printWriter.close();
}
}
System.exit(0);
}
EDIT: This is what I have made of the answers so far, please feel free to edit the wrong bit so I can clearly see what I've missed.
System.out.println("What's happening");
String path = System.getProperty("user.home") + File.separator + "Desktop/file1.txt";
File file = new File(path);
PrintWriter printWriter = null;
try
{
printWriter = new PrintWriter(file);
printWriter.println("hello");
FileWriter fileWriter = new FileWriter(file);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
if ( printWriter != null )
{
printWriter.close();
}
}
Also what about this:
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();
Rather a problem of directory
see this:
How to use PrintWriter and File classes in Java?
If the directory doesn't exist you need to create it. Java won't create it by itself since the File class is just a link to an entity that can also not exist at all.
// NOK for C:/Users see below
// File file = new File("C:/Users/Me/Desktop/file.txt");
File file = new File("C:/classical_dir/file.txt");
file.getParentFile().mkdirs();
PrintWriter printWriter = new PrintWriter(file);
This works well on my pc:
File file = new File("C:/foo/bar/blurps/file.txt");
This throws an exception: windows seems not to want it
File file = new File("C:/Users/Me/Desktop/file.txt");
because, C:/Users/Me seems to be prohibited: C:/Users seems to be protected by system
see this for writing in User directory: how can I create a file in the current user's home directory using Java?
String path = System.getProperty("user.home") + File.separator + "Desktop/file1.txt";
File file = new File(path);
see this also: How to get the Desktop path in java
Because File object does not create a physical copy of a file. For details follow this linkDoes creating a File object create a physical file or touch anything outside the JVM?
Now if we come to your solution then first make a empty file on the disk by following command
import java.io.*;
public class Test {
public static void main(String [] args) {
// The name of the file to open.
String fileName = "C:\\Users\\MOSSAD\\Desktop\\new\\temp.txt";
try {
// Assume default encoding.
FileWriter fileWriter =
new FileWriter(fileName);
File file = new File (fileName);
PrintWriter writer = new PrintWriter(file);
writer.println("Player 1 score: " + 5);
writer.println("Player 2 score: " + 2);
writer.println("Player 3 score: " + 3);
writer.println("Player 4 score: " + 4);
writer.close();
}
catch(IOException ex) {
System.out.println(
"Error writing to file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
you need to use double slash in path .link

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()) {

Categories

Resources