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
Related
This piece of code throws a FileNotFoundException, i'm sure the file exists in my working directory, am i doing something wrong?
private void generateInvoiceNumber(){ //uses reads previous invoice number and increments it.
try {
File invoiceFile = new File("./Invoices/invoiceFile.txt");
FileWriter writer = new FileWriter(invoiceFile,false);
Scanner getter = new Scanner(invoiceFile);
this.invoiceNumber = getter.nextInt();
writer.write(++invoiceNumber);
writer.close();
getter.nextInt();
getter.close();
}
catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
My tip:
Print (in your code) the current path location.
Then you can use this path in order to find the exact path you should use in order to access your file.
Maybe you should put more concrete absolute path:
File invoiceFile = Paths.get ("C:","Invoices", "invoiceFile.txt").toFile();
or if you trying to get from current path:
File invoiceFile = Paths.get (".","Invoices", "invoiceFile.txt").toFile();
And you can check your . path:
System.out.println(new File(".").getCanonicalPath());
Which operating system you are using?
It’s better to use paths when you are constructing a path to your file like
File file = Paths.get (".","Invoices", "invoice.txt").toFile();
corrected " symbols and default root "." which is your folder where app started.
I'm trying to create a folder under /usr in linux from a java program. Here's what I've done. I understand that I lack the permission to do so under /usr but what do I need to add?
public void createDirectory (String path)
{
File directory = new File(path);
if (!directory.exists()) {
if (!directory.mkdirs()) {
System.out.println("couldn't create file");
}
}
}
Here the sysout statement gets printed. what needs to be done here? Would greatly appreciate your help and thanks in advance.
mkdirs() is used in case you want to create nested folders.
Try with mkdir() instead:
public void createDirectory (String path)
{
File directory = new File(path);
if (!directory.exists()) {
if (!directory.mkdir()) {
System.out.println("couldn't create file");
}
}
}
Please note that you must provide the full path in order to make it work. Also as #Reimeus mentioned in the comment above, is not a good idea to write or create anything at that level, I would suggest to create it under /home/your_user/
I don't understand how to use TextIO's readFile(String Filename)
Can someone please explain how can I read an external file?
public static void readFile(String fileName) {
if (fileName == null) // Go back to reading standard input
readStandardInput();
else {
BufferedReader newin;
try {
newin = new BufferedReader( new FileReader(fileName) );
}
catch (Exception e) {
throw new IllegalArgumentException("Can't open file \"" + fileName + "\" for input.\n"
+ "(Error :" + e + ")");
}
if (! readingStandardInput) { // close current input stream
try {
in.close();
}
catch (Exception e) {
}
}
emptyBuffer(); // Added November 2007
in = newin;
readingStandardInput = false;
inputErrorCount = 0;
inputFileName = fileName;
}
}
I had to use TextIO for a school assignment and I got stuck on it too. The problem I had was that using the Scanner class I could just pass the name of the file as long as the file was in the same folder as my class.
Scanner fileScanner = new Scanner("data.txt");
That works fine. But with TextIO, this won't work;
TextIO.readfile("data.txt"); // can't find file
You have to include the path to the file like this;
TextIo.readfile("src/package/data.txt");
Not sure if there is a way to get it to work like the Scanner class or not, but this is what I've been doing in my course at school.
The above answer (about using the correct file name) is correct, however, as a clarification, make sure that you actually use the proper file path. The file path suggested above, i.e. src/package/ will not work in all circumstances. While this will be obvious to some, for those of you who need clarification, keep reading.
For example (and I use NetBeans), if you have already moved the file into NetBeans, and the file is already in the folder you want it to be in, then right click on the folder itself, and click 'properties'. Then expand the 'file path' section by clicking on the three dots next to the hidden file path. You will see the actual file path in its entirety.
For example, if the entire file path is:
C:\Users..\NetBeansProjects\IceCream\src\icecream\icecream.dat
Then, in the java code file itself, you can write:
TextIo.readfile("src/icecream/icecream.dat");
In other words, make sure you include the words 'src' but also everything that follows the src as well. If it's in the same folder as the rest of the files, you won't need anything prior to the 'src'.
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.
I've got a conditional to check if a certain file exists before proceeding (./logs/error.log). If it isn't found I want to create it. However, will
File tmp = new File("logs/error.log");
tmp.createNewFile();
also create logs/ if it doesn't exist?
No.
Use tmp.getParentFile().mkdirs() before you create the file.
File theDir = new File(DirectoryPath);
if (!theDir.exists()) theDir.mkdirs();
File directory = new File(tmp.getParentFile().getAbsolutePath());
directory.mkdirs();
If the directories already exist, nothing will happen, so you don't need any checks.
Java 8 Style
Path path = Paths.get("logs/error.log");
Files.createDirectories(path.getParent());
To write on file
Files.write(path, "Log log".getBytes());
To read
System.out.println(Files.readAllLines(path));
Full example
public class CreateFolderAndWrite {
public static void main(String[] args) {
try {
Path path = Paths.get("logs/error.log");
Files.createDirectories(path.getParent());
Files.write(path, "Log log".getBytes());
System.out.println(Files.readAllLines(path));
} catch (IOException e) {
e.printStackTrace();
}
}
}
StringUtils.touch(/path/filename.ext) will now (>=1.3) also create the directory and file if they don't exist.
No, and if logs does not exist you'll receive java.io.IOException: No such file or directory
Fun fact for android devs: calls the likes of Files.createDirectories() and Paths.get() would work when supporting min api 26.