I keep getting a "File not found exception", but I know it's there! File file = new File("C:\\A-small-practice.in"); is able to find the file fine, but when I try to use FileInputStream it returns an exception.
import java.io.*;
public class Solution {
public static void main(String[] args) {
File file = new File("C:\\A-small-practice.in");
System.out.println(file.getAbsolutePath()); //prints C:\A-small-practice.in
FileInputStream fstream = new FileInputStream(file);
}
}
The File has some methods that can help you.
boolean canExecute();
boolean canRead();
boolean canWrite();
boolean exists();
boolean isFile();
boolean isDirectory();
boolean isAbsolute()
For example, you could check for: exists() && isFile() && canRead() and print a better error-message depending on the reason why you cant read the file.
When you write :
File file = new File("C:\\A-small-practice.in");
A file will be made if one dosen't exist, so there will be no reason for
you the get an exception when call file.getAbsolutePath()).
However if the file didn't exist it will throw a file not found exception,
once you try to open an input stream for a non existing file.
So my suggestion is try calling .exsits(). To see if the file do exist.
Also the java documenation for the file not found exception says the following :
"It will also be thrown by these constructors if the file does exist but for some reason is inaccessible".
So perhaps you should share some info on the file itself.
Related
We need to call file.exists() before file.delete() before we can delete a file E.g.
File file = ...;
if (file.exists()){
file.delete();
}
Currently in all our project we create a static method in some util class to wrap this code. Is there some other way to achieve the same , so that we not need to copy our utils file in every other project.
Starting from Java 7 you can use deleteIfExists that returns a boolean (or throw an Exception) depending on whether a file was deleted or not. This method may not be atomic with respect to other file system operations. Moreover if a file is in use by JVM/other program then on some operating system it will not be able to remove it. Every file can be converted to path via toPath method . E.g.
File file = ...;
boolean result = Files.deleteIfExists(file.toPath()); //surround it in try catch block
file.delete();
if the file doesn't exist, it will return false.
There's also the Java 7 solution, using the new(ish) Path abstraction:
Path fileToDeletePath = Paths.get("fileToDelete_jdk7.txt");
Files.delete(fileToDeletePath);
Hope this helps.
Apache Commons IO's FileUtils offers FileUtils.deleteQuietly:
Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories.
The difference between File.delete() and this method are:
A directory to be deleted does not have to be empty.
No exceptions are thrown when a file or directory cannot be deleted.
This offers a one-liner delete call that won't complain if the file fails to be deleted:
FileUtils.deleteQuietly(new File("test.txt"));
I was working on this type of function, maybe this will interests some of you ...
public boolean deleteFile(File file) throws IOException {
if (file != null) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f: files) {
deleteFile(f);
}
}
return Files.deleteIfExists(file.toPath());
}
return false;
}
if you have the file inside a dirrectory called uploads in your project. bellow code can be used.
Path root = Paths.get("uploads");
File existingFile = new File(this.root.resolve("img.png").toUri());
if (existingFile.exists() && existingFile.isFile()) {
existingFile.delete();
}
OR
If it is inside a different directory this solution can be used.
File existingFile = new File("D:\\<path>\\img.png");
if (existingFile.exists() && existingFile.isFile()) {
existingFile.delete();
}
Use the below statement to delete any files:
FileUtils.forceDelete(FilePath);
Note: Use exception handling codes if you want to use.
Use Apache Commons FileUtils.deleteDirectory() or FileUtils.forceDelete() to log exceptions in case of any failures,
or FileUtils.deleteQuietly() if you're not concerned about exceptions thrown.
Generally We create the File object and check if File Exist then delete.
File f1 = new File("answer.txt");
if(f1.exists()) {
f1.delete();
}
OR
File f2 = new File("answer.txt");
f2.deleteOnExit();
If you are uses the Apache Common then below are the option using which you can delete file and directory
File f3 = new File("answer.txt");
FileUtils.deleteDirectory(f3);
This method throws the exception in case of any failure.
OR
File f4 = new File("answer.txt");
FileUtils.deleteQuietly(f4);
This method will not throw any exception.
This is my solution:
File f = new File("file.txt");
if(f.exists() && !f.isDirectory()) {
f.delete();
}
File xx = new File("filename.txt");
if (xx.exists()) {
System.gc();//Added this part
Thread.sleep(2000);////This part gives the Bufferedreaders and the InputStreams time to close Completely
xx.delete();
}
My goal
I am trying to write simple objects (SimpleType) into files, so that the files can be loaded later and the objects recreated.
My setting
I am currently working in the NetBeans IDE (JDK8) on a Windows 7 machine. I don't think that should make a difference, though.
This is the type I would like to write into the file:
public class SimpleType implements Serializable {
boolean[] a;
boolean[] b;
}
This is the code I'm trying to get to run:
public class Test {
public static void main(String[] args)
throws IOException, ClassNotFoundException {
String fileName = "test.txt";
SimpleType foo = new SimpleType;
try (ObjectOutputStream out = new ObjectOutputStream(new
BufferedOutputStream(new FileOutputStream(fileName)))) {
out.writeObject(foo);
out.close();
}
}
}
My problem
The code compiles and runs, but always throws a FileNotFoundException:
Exception in thread "main" java.io.FileNotFoundException: test.txt (Access is denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at java.io.FileOutputStream.<init>(FileOutputStream.java:101)
at Test.main(Test.java:33)
My attempts to fix it
According to the documentation, I would expect the file to be created if it doesn't exist already. I've thoroughly read the Javadoc for the method I attempt to use, an excerpt of which I cite here (emphasis mine):
public FileOutputStream(String name) throws FileNotFoundException
[...]
Parameters:
name - the system-dependent filename
Throws:
FileNotFoundException - if the file exists but is a directory rather
than a regular file, does not exist but cannot be created, or cannot
be opened for any other reason
SecurityException - if a security manager exists and its checkWrite
method denies write access to the file.
I am sure that I have read/write permissions in the directory; there is no existing file with the name test.txt so it cannot be locked by another program.
Changing fileName to an absolute path I am sure I can write into doesn't make any difference.
It is reproducible if file is in read-only mode. Can you try like this.
public static void main(String[] args) {
String fileName = "sampleObjectFile.txt";
SampleObject sampleObject = new SampleObject();
File file = new File(fileName);
file.setWritable(true); //make it writable.
try(ObjectOutputStream outputStream = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)))){
outputStream.writeObject(sampleObject);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
If you are writing the file on OS disk you need admin privileges. so avoid writing on OS disk.
Normally this is because you are trying to write on a location not allowed by your FileSystem (for example in Windows7 you cannot write a new file in c:). Try to investigate where the program is trying to write using procmon from Microsoft's SysInternals. Add a new filter (path contains test.txt) and see what happens.
I'm very new at coding java and I'm having a lot of difficulty.
I'm suppose to write a program using bufferedreader that reads from a file, that I have already created named "scores.txt".
So I have a method named processFile that is suppose to set up the BufferedReader and loop through the file, reading each score. Then, I need to convert the score to an integer, add them up, and display the calculated mean.
I have no idea how to add them up and calculate the mean, but I'm currently working on reading from the file.
It keeps saying that it can't fine the file, but I know for sure that I have a file in my documents named "scores.txt".
This is what I have so far...it's pretty bad. I'm just not so good at this :( Maybe there's is a different problem?
public static void main(String[] args) throws IOException,
FileNotFoundException {
String file = "scores.txt";
processFile("scores.txt");
//calls method processFile
}
public static void processFile (String file)
throws IOException, FileNotFoundException{
String line;
//lines is declared as a string
BufferedReader inputReader =
new BufferedReader (new InputStreamReader
(new FileInputStream(file)));
while (( line = inputReader.readLine()) != null){
System.out.println(line);
}
inputReader.close();
}
There are two main options available
Use absolute path to file (begins from drive letter in Windows or
slash in *.nix). It is very convenient for "just for test" tasks.
Sample
Windows - D:/someFolder/scores.txt,
*.nix - /someFolder/scores.txt
Put file to project root directory, in such case it will be visible
to class loader.
Place the scores.txt in the root of your project folder, or put the full path to the file in String file.
The program won't know to check your My Documents folder for scores.txt
If you are using IntelliJ, create an input.txt file in your package and right click the input.txt file and click copy path. You can now use that path as an input parameter.
Example:
in = new FileInputStream("C:\\Users\\mda21185\\IdeaProjects\\TutorialsPointJava\\src\\com\\tutorialspoint\\java\\input.txt");
Take the absolute path from the local system if you'r in eclipse then right-click on the file and click on properties you will get the path copy it and put as below this worked for me In maven project keep the properties file in src/main/resources `
private static Properties properties = new Properties();
public Properties simpleload() {
String filepath="C:/Users/shashi_kailash/OneDrive/L3/JAVA/TZA/NewAccount/AccountConnector/AccountConnector-DEfgvf/src/main/resources/sample.properties";
try(FileInputStream fis = new FileInputStream(filepath);) {
//lastModi = propFl.lastModified();
properties.load(fis);
} catch (Exception e) {
System.out.println("Error loading the properties file : sample.properties");
e.printStackTrace();
}
return properties;
}`
This doesn't seem to create a file or folder. Why?
import java.io.*;
public class file1
{
public static void main(String[] args)
{
File text1 = new File("C:/text1.txt");
File dir1 = new File("C:/dir");
}
This one below does create a file.
import java.io.*;
public class file3
{
public static void main(String[] args)
{
try
{
FileWriter text1 = new FileWriter("C:/text.txt");
FileWriter dir = new FileWriter("C:/dir");
}
catch(Exception e){}
}
}
However, the directory seems to have a strange unusable icon.
What can I do to create a directory.
What are other simple methods to create files and folders.
Surprisingly, the File class does not represent a file. It actually represents a pathname for a file ... that may or may not exist.
To create a file in Java, you need to open it for output; e.g.
File text1 = new File("C:/text1.txt");
FileOutputStream os = new FileOutputStream(text1); // The file is created
// here ... if it doesn't
// exist already.
// then write to the file and close it.
or you could do this - new FileOutputStream("C:/text1.txt"). In both cases, an existing file will be truncated ... unless you use the FileOutputStream with a boolean parameter that says open for appending.
If you want to create a file without writing any data to it, you could also do this:
File text1 = new File("C:/text1.txt");
text1.createNewFile();
However, that will only create a new file if the file didn't already exist.
To create a directory in Java, use the File.mkdir() or File.mkdirs() methods.
UPDATE
You commented:
I tried File dir = new File("C:/dir1").mkdir(); it says incompatible types.
That is right. The mkdir() method returns a boolean to say whether or not it created the directory. What you need to write is something like this:
File dir = new File("C:/dir1");
if (dir.mkdir()) {
System.out.println("I created it");
}
Always READ THE JAVADOCS before using a method or class you are not familiar with!
A couple more things you need to know:
The best way to deal with the problem of making sure a file gets closed is to do something like this:
try (FileOutputStream os = new FileOutputStream(text1)) {
// now write to it
}
The stream os will be closed automatically when the block exits.
It is usually "bad practice" to catch Exception. It is always "bad practice" to catch Exception and do nothing in the handler. This kind of this hides the evidence of bugs, and makes your code unpredictable and hard to debug.
If you're creating a directory with File, you want this:
new File("C:/dir").mkdirs();
For creating directory you can use :
if(!text1.exists()){
text1.mkdir();
}
and for creating file use:
if(!text1.exists()){
try {
text1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
For whatever reason I am having an issue with File.delete() and File.renameto(File). For example:
private void doWork(){
File inputFile = new File("resources/custom/inputFile.txt");
System.out.println(inputFile.delete());
}
This returns false for me and does not delete the file.
I don't have this file opened or in use anywhere else and I don't understand why I can't delete it. Has anyone else encountered this or have any insight into the problem?
Try adding a line:
System.out.println(inputFile.getCanonicalPath());
This will print the actual path (starting from the root) and maybe reveal that it isn't the path you're expecting.
try this
private void doWork(){
File inputFile = new File("resources\\custom\\inputFile.txt");
System.out.println(inputFile.delete());
}
also it will help if you add try and catch