Exception when trying to start a program when a file already exists - java

I have an application that writes text to a File. If the File doesn't exist, it is created.
When I run the application for the first time, it all works correctly and the File is created. However, every subsequent time causes the application to crash. Could you please help explain why it doesn't work more than once.
My code is as follows...
public class Apples {
Formatter x;
File file = new File("myfile.txt");
public Apples() {
if (!file.exists()) {
try {
x = new Formatter("myfile.txt");
}
catch (Exception e) {
System.out.println("There was an error creating the file");
}
System.out.println("The file was created");
}
else {
System.out.println("The file already exists");
}
x.format("%s", "text");
x.close();
}
public static void main(String[] args) throws FileNotFoundException {
Apples a = new Apples();
}
}

I suspect that the problem is a NullPointerException on the line x.format("%s", "text"); because you aren't assigning a value to x if the file already exists.

Second time x is null because you don't init it.

Related

How to write file path into txt.file?

I am writing simple program that is looking for file and if it exists, writes his path to txt file. If not, program is freezed for 1 minute. My problem is that file path is not being printed into txt file when searched file exists. I think it is something wrong with try block. I do not know where the problem is. How can i solve it?
public class FileScanner {
public void scanFolder() throws IOException, InterruptedException {
Scanner input = new Scanner(System.in);
//tworzenie pliku logu
File log = new File("C:/Users/mateu/OneDrive/Pulpit/log.txt");
if (!log.exists()) {
log.createNewFile();
}
//obiekt zapisujacy nazwy i sciezki plikow do logu
PrintWriter printIntoLog = new PrintWriter(log);
while (true) {
//podanie sciezki szukanego pliku
System.out.println("Input file's directory you are looking for: ");
String path = input.nextLine();
//utworzenie obiektu do danego pliku
File searchedFile = new File(path);
//sprawdzenie czy plik istnieje- jesli tak to zapisuje do logu jego sciezke i usuwa go
try{
if (searchedFile.exists()) {
printIntoLog.println(searchedFile.getPath());
//searchedFile.delete();
}else{
throw new MyFileNotFoundException("Searching stopped for 1 minute.");
}
}catch(MyFileNotFoundException ex){
System.out.println(ex);
TimeUnit.MINUTES.sleep(1);
}
}
}
}
You should close the PrintWriter reference before finishing execution. It's an enforced practice to close a file after read/write on it.
If you are using Java +7 you can use the fancy way withtry-with-resources syntax
```java
try (PrintWriter printIntoLog = new PrintWriter(log)) {
while (true) {
....
}
}
```
With older versions you can use try-finally syntax
try {
while(true) {
...
}
} finally {
printIntoLog.close();
}
See
Java – Try with Resources

How to solve my try-catch exception handling?

I'm having problems with my try-catch exception here. Actually what it does is to prompt the user for the name of a text file say, Robot.txt but if say the file does not exist, I have to make sure that the application reprompts the user for the file name. Hope you guys can understand I'm still a newbie here so please feel free to provide suggestions or advices on my coding etc. Cheers!
Main method class:
import java.io.*;
import java.util.Scanner;
import java.util.Vector;
class TestVector3 {
public static void main(String [] args)
{
System.out.println("Please enter the name of the text file to read: ");
Scanner userInput = new Scanner(System.in);
Vector <KillerRobot> robotDetails = new Vector <KillerRobot>();
KillerRobot robot;
Scanner fileInput = null;
try
{
File textFile = new File(userInput.nextLine());
fileInput = new Scanner(textFile);
}
catch (FileNotFoundException e)
{
System.out.println("Error - file not found!");
System.out.println("Re-enter file name :"); //Reprompt user for name of the text file
fileInput = new Scanner(userInput.nextLine());
}
while(fileInput.hasNext())
{
robot = new KillerRobot();
String first = fileInput.next();
robot.setName(first);
String second = fileInput.next();
robot.setMainWeapon(second);
int third = fileInput.nextInt();
robot.setNumberOfKills(third);
robotDetails.add(robot);
}
for(KillerRobot i : robotDetails)
{
System.out.println(i);
}
fileInput.close();
}
}
KillerRobot class file:
class KillerRobot {
private String name;
private String mainWeapon;
private int numberOfKills;
KillerRobot()
{
}
public String getName()
{
return name;
}
public String getMainWeapon()
{
return mainWeapon;
}
public int getNumberOfKills()
{
return numberOfKills;
}
public String toString()
{
return name + " used a " + mainWeapon + " to destroy " + numberOfKills + " enemies ";
}
public void setName(String a)
{
name = a;
}
public void setMainWeapon(String b)
{
mainWeapon = b;
}
public void setNumberOfKills(int c)
{
numberOfKills = c;
}
}
As you state that you are a beginner, let us first look at the relevant part of your code, to make sure that we talk about the same thing:
Scanner fileInput = null;
try {
File textFile = new File(userInput.nextLine());
fileInput = new Scanner(textFile);
}
catch (FileNotFoundException e) {
System.out.println("Error - file not found!");
System.out.println("Re-enter file name :");
fileInput = new Scanner(userInput.nextLine());
}
You have an input and you want to check this input for a condition and require a new input until this condition is fulfilled. This problem can be solved using a loop like the following:
Scanner fileInput = null;
do {
System.out.println("Enter file name :");
try {
fileInput = new Scanner(new File(userInput.nextLine()));
} catch (FileNotFoundException e) {
System.out.println("Error - file not found!");
}
} while(fileInput == null);
So finally, why does this work? The fileInput variable is set to null and will remain null until the given file is successfully read from standard input because an exception is thrown otherwise what prevents the fileInput variable to be set. This procedure can be repeated endlessly.
On a side note, for performance reasons, it is normally not a good idea to implement control flow that is based on exceptions. It would be better to check for a condition if a file exists via File::exists. However, if you read the file after checking for its existence, it might have been deleted in the meantime which introduces a racing condition.
Answer to your comment: In Java (or almost any programming language), you can inline expressions. This means that instead of calling two methods in two different statements as in
Foo foo = method1();
Bar bar = method2(foo);
you can simply call
Bar bar = method2(method1());
This way, you save yourself some space (what becomes more and more important if your code gets longer) as you do not need the value that you saved in foo at any other place in your code. Similarly, you can inline (which is how this pattern is called) from
File file = new File(userInput.nextLine())
fileInput = new Scanner(file);
into
fileInput = new Scanner(new File(userInput.nextLine()));
as the file variable is only read when creating the Scanner.
Try putting the try-catch in a loop like below:
Scanner fileInput = null;
while (fileInput==null)
{
try
{
System.out.println("Please enter the file name.");
File textFile = new File(userInput.nextLine());
fileInput = new Scanner(textFile);
}
catch (FileNotFoundException e)
{
System.out.println("Error - file not found!");
}
}
Next you could think of moving the File creation part into separate method, so that the code was cleaner.
Do not fall for try-catch instead add this as your functionality. Exceptions are naturally for run time error handling not for logic building.
Check if file exists at given location.
File textFile = new File(userInput.nextLine());
// Check if file is present and is not a directory
if(!textFile.exists() || textFile.isDirectory()) {
System.out.println("Error - file not found!");
//Reprompt user for name of the text file
System.out.println("Re-enter file name :");
fileInput = new Scanner(userInput.nextLine());
}
You can put while loop instead of if loop if you want to continuously prompt user until correct path is entered.
You can call back your main(), like following
try
{
File textFile = new File(userInput.nextLine());
fileInput = new Scanner(textFile);
}
catch (FileNotFoundException e)
{
System.out.println("Error - file not found!");
main(args); // recursively call main() method
}
Now if user first attempt wrong then your code will asked to re enter file name.
How to check isFile exist?
File file = new File(filePathString);
if(file.exists() && !file.isDirectory()){
System.out.println("file exist");
}
This really is an XY problem because you assumed the only way to check for a file existence is by catching a FileNotFoundException (hence asking about try-catch exception handling) whereas other means exist to help you avoid a try-catch idiom in an elegant manner.
To check if a file exists at the given path or not you can simply use the File.exists method. Please also see the File.isFile method and/or the File.isDirectory method to verify the nature of the targeted File object.
EDIT : As stated by raphw, this solution is best used in simple scenario since it can incur a race condition in the case of concurrent file deletion happening during the file existence check. See his answer for handling more complex scenario.

Creating a simple data output file in Java

I am trying to write a simple data output file. When I execute the code I get a "No file exist" as the output and no data.txt file is created in the dir.
What am I missing? The odd thing is that it was working fine the other night, but when I loaded it up today to test it out again, this happened.
Here is the code:
import java.io.*;
import java.util.*;
public class DataStreams {
public static void main(String[] args) throws IOException {
try {
DataOutputStream out = new DataOutputStream(new FileOutputStream("C:\\data.txt"));
for (int i = 0; i < 10; i++) {
out.write(i);
}
} catch (IOException ioe) {
System.out.println("No file exist");
}
}
}
The data file should be a simple display of numbers 1 through 9.
Thanks for your input.
On Windows platforms, C:\ is a restricted path by default. Previously the application may have been run as administrator allowing access.
Solution: Use a different location
DataOutputStream out =
new DataOutputStream(new FileOutputStream("C:/temp/data.txt"));
Create a text file named data.txt in c: .You must have deleted the file. Creating that file manually will work
You should have a look at the exception itself:
System.out.println("No file exist");
System.out.println(ex.getMessage());
Perhaps you have not the necessary rights, to access C:\ with your program.
To write data into a file, you should first create it, or, check if it exists.Otherwise, an IOException will be raised.
Writing in C:\ is denied by default, so in your case even if you created the file you will get an IOException with an Access denied message.
public static void main(String[] args) throws IOException {
File output = new File("data.txt");
if(!output.exists()) output.createNewFile();
try {
DataOutputStream out = new DataOutputStream(new FileOutputStream(output));
for (int i = 0; i < 10; i++) {
out.write(i);
}
} catch (IOException ioe) {
System.out.println("No file exist");
}
}

Unhandled Exception Type FileNotFoundException

Main class:
public class cfung58_lab03_Main {
//main class
//creates objects
//Unhandled Exception Type FileNotFoundException occurs on the line below
static cfung58_lab03_Department myDepartment = new cfung58_lab03_Department();
...
}
Department Class:
public class cfung58_lab03_Department {
....
static cfung58_lab03_Course[] coursesArray;
static cfung58_lab03_Student[] studentArray;
public cfung58_lab03_Department() throws FileNotFoundException{
File file = new File("Courses.txt"); //file for Courses.txt
//System.out.println(file.getCanonicalPath());//gets path
//File file2 = new File("Students.txt"); //file for Students.txt
//System.out.println("True or false: " + file.canRead());
if (file.exists()){
//if the course file exists
//load scanner object to read file course.txt string
//NOTE: remember to throw FileException
Scanner read = new Scanner(file);
//count the number of Courses first before
// creating the coursesArray and filling in the elements
int numberOfCourses = 0;
while (read.hasNext()){
//String courseName = read.next();
numberOfCourses++;
}
//create coursesArray
cfung58_lab03_Course[] coursesArray = new cfung58_lab03_Course[numberOfCourses];
//restart the scanner system for read
read = new Scanner(file);
while (read.hasNext()){
String courseName = read.next();
//for loop to fill in the elements for coursesArray
for (int i = 0 ; i < numberOfCourses ; i++){
//creating element
coursesArray[i] = new cfung58_lab03_Course(courseName, 0 );
}
}
}
//else throw exception
else
throw new FileNotFoundException("File could not be found.");
I'm not exactly sure what's causing the compiler error even though I've already thrown the exception on the department constructor.
Eclipse has no solution to it either.
Any idea what might be causing this?
You're calling a method, from your horribly named main class, and this method throws a checked exception. So this exception needs to be caught (or thrown, but you can't thow it here since you're assigning a static variable out of a method):
static cfung58_lab03_Department myDepartment;
static {
try {
myDepartment = new cfung58_lab03_Department();
}
catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
That said, this field should probably be a local variable of your main method instead.
Delete " throws FileNotFoundException" and use "try&catch" to get the error. You'll be proximate to the error line.
The solution here is to create a static initialization block:
static cfung58_lab03_Department myDepartment;
static {
try {
myDepartment = new cfung58_lab03_Department();
} catch (FileNotFoundException e) {
throw new ExceptionInInitializerError(e);
}
}
Either this, or in your Department constructor, throw an unchecked exception instead.
In your code cfung58_lab03_Department you are throwing exception in else case as..
//else throw exception
else
throw new FileNotFoundException("File could not be found.");
means if your code does not found file on mentioned path it will default throw an exception.
Try following ways to get file "Courses.txt" correctly,
// Collect file with proper known path
File file = new File("resources\file_path\Courses.txt");
// Collect file with Input Stream
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("Courses.txt");

problem with deleting files

private static void deletefile(String file) {
int fileName = 500;
int z;
String[] File = new String[fileName];
for (z = 0; z < fileName; z++) {
File f1 = new File(
"C:\\Users\\user\\fypworkspace\\TextRenderer\\abc" + z
+ ".txt");
boolean success = f1.delete();
if (!success) {
System.out.println("Deletion failed.");
System.exit(0);
} else {
System.out.println("File deleted.");
}
}
}
public static void main(String[] args) throws IOException {
switch (args.length) {
case 0:
System.out.println("File has not mentioned.");
System.exit(0);
case 1:
deletefile(args[0]);
System.exit(0);
default:
System.out.println("Multiple files are not allow.");
System.exit(0);
hi, this is my code for attempting to delete a certain files in java. It prints out file has not mentioned.i was trying to delete a set of txt files in a certain folder. The program should continue with the next file once a file is missing. Can anyone point out my mistake ? thanks..
Apparently you did not pass any command line parameters to your program.
(Although even if you did, it is not used anywhere in deletefile() - your method attempts to delete a fixed set of files in a specific directory, and if any of these is missing or you don't have permissions to delete it, it exits with an error message.)
You have to specify the file name as command line argument when running your Java program.
java MyClass file_to_delete
You need to have some check or catch exception when you create a new file so it wont stop when the file is not found.

Categories

Resources