I want to get the filename of the file that do not exist when a file exception occur in my java application so that i can give a short message to the user.
catch (FileNotFoundException e) {
/* what code to put here to get the filename of the file */
}
This should display the non-existing file path:
try {
//access file
} catch(FileNotFoundException e) {
System.out.println(e.getMessage());
}
Output, for creating a Scanner with new Scanner(new File("C:/filetest")):
C:\filetest (The system cannot find the file specified)
You cannot grap properly the filename unless you parse the stacktrace in your catch block.
You can either store the filename outside of the try block, i.e.:
String filename = ...
try {
// process file
} catch (FileNotFoundException e) {
String message = String.format("The file % could not be found.", filename);
// Show message to user
}
Or you can check whether the file exists before trying to access it:
File file = new File(filename);
if (!file.exists()) {
// Show error to user.
}
Related
I wonder why my program overwrites existing text in the textfile instead of adding a new line of text?
public class WriteToFile {
public void registerTrainingSession(Customer customer) {
Path outFilePath = Paths.get("C:\\Users\\Allan\\Documents\\Nackademin\\OOP\\Inlämningsuppgift2\\visits.txt");
try (BufferedWriter save = Files.newBufferedWriter(outFilePath)) {
String trainingSession = String.format("Member: %s %s\nPersonalnumber: %s\nTraining session date: %s\n", customer.getFirstName(),
customer.getLastName(), customer.getPersonalNumber(), LocalDate.now());
save.write(trainingSession);
save.flush();
}
catch (NullPointerException e) {
JOptionPane.showMessageDialog(null, "Customer info is missing!");
}
catch (IOException e) {
JOptionPane.showMessageDialog(null, "File could not be created.");
}
}
}
The code overwrites the file because you didn't specify an OpenOption on the newBufferedWriter() call.
As the javadoc says:
If no options are present then this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of 0 if it exists.
Try:
Files.newBufferedWriter(outFilePath, StandardOpenOption.CREATE,
StandardOpenOption.APPEND,
StandardOpenOption.WRITE)
Or if the file must already exist, failing if it doesn't:
Files.newBufferedWriter(outFilePath, StandardOpenOption.APPEND,
StandardOpenOption.WRITE)
To write a new file, failing if it already exists
Files.newBufferedWriter(outFilePath, StandardOpenOption.CREATE_NEW,
StandardOpenOption.WRITE)
I am generating a file using the following syntax
File file = new File("input.txt");
The problem is that it is saying that it is writing to the file but I am not able to locate where the file is created, I searched my entire workspace. The expectation was that it would be created in the same folder as my code which is executing.
Any ideas?
Rest of the code :
File file = new File("input.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
You could do a sop on the absolute path and you would get the path:
File file = new File("input.txt");
System.out.println("" + file.getAbsolutePath());
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
When you create file through relative paths, Java uses System.getProperty("user.dir"). So, in your case the full path to file will be System.out.println(System.getProperty("user.dir") + "/input.txt");.
I want to read file content using this code:
String content = new String(Files.readAllBytes(Paths.get("/sys/devices/virtual/dmi/id/chassis_serial")));
On some systems this file is not present or it's empty. How I catch this exception? I want to print message "No file" when there is no file and there is no value.
The AccessDeniedException can be thrown only when using the new file API. Use an inputStream to open a stream from the source file so that you could catch that exception.
Try with this code :
try
{
final InputStream in = new Files.newInputStream(Path.get("/sys/devices/virtual/dmi/id/chassis_serial"));
} catch (FileNotFoundException ex) {
System.out.print("File not found");
} catch(AccessDeniedException e) {
System.out.print("File access denied");
}
Try to use filter file.canRead()) to avoid any access exceptions.
Create a File object and check if it exists.
If it does then it's safe to convert that file to a byte array and check that the size is greater then 0. If it is convert it to a String. I added some sample code below.
File myFile = new File("/sys/devices/virtual/dmi/id/chassis_serial");
byte[] fileBytes;
String content = "";
if(myFile.exists()) {
fileBytes = File.readAllBytes(myfile.toPath);
if(fileBytes.length > 0) content = new String(fileBytes);
else System.out.println("No file");
else System.out.println("No file");
I know it's not the one liner you were looking for. Another option is just to do
try {
String content = new String(Files.readAllBytes(Paths.get("/sys/devices/virtual/dmi/id/chassis_serial")));
} catch(Exception e) {
System.out.print("No file exists");
}
Read up on try catch blocks here like MrTux suggested, as well as java Files and java io here.
This is my file directory
I am trying to open admin.dat for reading but dont understand why am i unable to open the file and the FileNotFound exception is always thrown
Code:
public void readfile(){
try{
Scanner filereader = new Scanner(new File("admin.dat"));
String data;
while(filereader.hasNextLine()){
data = filereader.nextLine();
System.out.println(data);
}
}
catch (FileNotFoundException e){
System.out.println("File not found");
}
catch (IOException e){
System.out.println("Error while reading file");
}
}
Generally when you launch app through IDE they set current directory to the root of the project so you need to pass relative path from there
You can check what is set as current directory by
System.out.println(System.getProperty("user.dir"));
ALso it will just work as long as the file exists as a real File, if you bundle it in jar or some other form of archive it will stop working, so better to read it as Resource from classpath
I am trying to create a file inside a directory using the following code:
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("themes", Context.MODE_WORLD_WRITEABLE);
Log.d("Create File", "Directory path"+directory.getAbsolutePath());
File new_file =new File(directory.getAbsolutePath() + File.separator + "new_file.png");
Log.d("Create File", "File exists?"+new_file.exists());
When I check the file system of emulator from eclipse DDMS, I can see a directory "app_themes" created. But inside that I cannot see the "new_file.png" . Log says that new_file does not exist. Can someone please let me know what the issue is?
Regards,
Anees
Try this,
File new_file =new File(directory.getAbsolutePath() + File.separator + "new_file.png");
try
{
new_file.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("Create File", "File exists?"+new_file.exists());
But be sure,
public boolean createNewFile ()
Creates a new, empty file on the file system according to the path information stored in this file. This method returns true if it creates a file, false if the file already existed. Note that it returns false even if the file is not a file (because it's a directory, say).
Creating a File instance doesn't necessarily mean that file exists. You have to write something into the file to create it physically.
File directory = ...
File file = new File(directory, "new_file.png");
Log.d("Create File", "File exists? " + file.exists()); // false
byte[] content = ...
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
out.write(content);
out.flush(); // will create the file physically.
} catch (IOException e) {
Log.w("Create File", "Failed to write into " + file.getName());
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
Or, if you want to create an empty file, you could just call
file.createNewFile();
Creating a File object doesn't mean the file will be created. You could call new_file.createNewFile() if you wanted to create an empty file. Or you could write something to it.