Cannot Access Folder in java - java

I need my program to be able to read the files inside a folder, however when I try to compile I'm getting the following error: java.io.FileNotFoundException: (Access is denied)
Here is a section of my code:
String filename="FileCount"; //Replace this with file containing names of files to be processed
File file=new File(filename);

Here's a simple example. I hope this is what you're looking for
import java.io.File;
public class Files {
public void listFiles(){
String folderPath = "C:/Users/*****/Desktop"; // or as required
File file = new File(folderPath);
File[] files = file.listFiles();
for (File fileName : files) {
System.out.println(fileName); //Do what you need here... I'm just printing to console.
}
}
}

Related

How to read files from the sub folder of resource folder

How to read files from the sub folder of resource folder.
I have some json file in resources folder like :
src
main
resources
jsonData
d1.json
d2.json
d3.json
Now I want to read this in my class which is
src
main
java
com
myFile
classes
here is what I am trying but getting failed.
File folder = new File("./src/main/java/resources/jsonData/");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile()) {
// my operation of Data.
}
}
Not working then I am trying :
Resource resource = new ClassPathResource("classpath:jsonData/data1.json");
File folder = new File(resource.getURI());
File[] listOfFiles = folder.listFiles();
both of things are not working.
You should be able to achieve this using getClass.GetResource()
File[] fileList = (new File(getClass().getResource("/exampleFolder").toURI())).listFiles();

File (.txt) cannot be found

I am creating a stock market simulator (beginner) and I made a .txt file to save the stock symbol and name within a file. I am having an issue where my code is unable to find the file on my desktop.
public static void load() throws FileNotFoundException {
File file = new File("/Users/dhruvchaudhari/Desktop/stocks.txt");
Scanner scan = new Scanner(file);
while ((scan.hasNextLine())) {
System.out.println(scan.nextLine());
}
}
The error it is throwing is as such
java.io.FileNotFoundException: /Users/*username*/Desktop/stocks.txt (No such file or directory)
I'm on Mac and I checked the directory for the file directory and it should be correct. Any suggestions?
You can check the current working directory to confirm the path of your file by adding System.out.println("Working Directory = " + System.getProperty("user.dir"));
this will return the path you can debug this to get the idea of path in your application.
Also you can add read the file if its not there the code will create it for so you can add your metadata into the generated file.
By using this approach I hope you can move ahead.
public static void load() throws IOException {
File yourFile = new File(path);
yourFile.createNewFile(); // if file already exists will do nothing
Scanner scan = new Scanner(yourFile);
while ((scan.hasNextLine())) {
System.out.println(scan.nextLine());
}
}
Obviously your path is wrong or the file doesn't exist. You can use the if statement to determine whether the file exists first, and create the file when it does not exist.

Not able to access file in eclipse gives : FileNotFoundException

In eclipse i am trying to give path of one configuration.json file but it is not taking it .
System.getProperty("user.dir")
gives C:\Users\cmalik\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Eclipse
and
try {
File f = new File("."); // current directory
File[] files = f.listFiles();
for (File file : files) {
if (file.isDirectory()) {
System.out.print("directory:");
} else {
System.out.print(" file:");
}
System.out.println(file.getCanonicalPath());
}
gives
file:C:\Users\cm\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Eclipse\Eclipse Jee Neon.lnk
file:C:\Users\cm\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Eclipse\hs_err_pid10180.log
file:C:\Users\cm\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Eclipse\hs_err_pid9728.log
And my project structure is
ProjectName
---src
---- com.abc.def.ghi.jkl.WebServices
------ myService.java
---configuration.json
I tried code for accessing file is :
FileReader file = new FileReader("configuration.json");
or
FileReader file = new FileReader("projectName\\configuration.json");
It is not able to access as output for System.getProperty("user.dir") is eclipse folder not my current projectName folder.
How can i get my files please let me know.
You can use either of the below two:
String location=System.getProperty("user.dir");
or
String location= new java.io.File(".").getCanonicalPath();
And then try to access the file using:
FileReader file = new FileReader(location+"\\configuration.json");
Hope it helps.

Java code to rename a file and replace another file in same location

I have two files file1.txt1 and file2.txt in the same location as D:\Folder\. I have different contents in both files. Now i want to rename file2.txt as file1.txt and replace the already existing file1.txt. This way only one file will be left, that will be named as file1.txt and the contents will be of the file2.txt. How can i do this in Java?
I have tried to do the following, but the first file gets deleted and the second file wont get renamed.
File file1 = new File("D:\\Folder\\file1.txt");
File file2 = new File("D:\\Folder\\file2.txt");
file1.delete();
file2.renameTo(new File("D:\\Folder\\file1.txt"));
Thank you so much for your help. Please find the solution
import java.io.File;
import java.io.IOException;
public class TextFileRenaming {
public static void main(String[] args) throws IOException {
//File directory
File file = new File("C:/Folder/");
// Reading directory contents
File[] files = file.listFiles();
String name = null;
for(File f : files){
// Getting file name and deleting
if(f.getName() != null && f.getName().equals("file1.txt")){
name = f.getName();
f.delete();
// Renaming the file
file.listFiles()[0].renameTo(new File(file.getAbsolutePath() + "\\"+ name));
}
}
}
}

Access file without filename

I have a folder in a directory. I know, there is always only one file and it's a .txt file. But I don't know the filename.
How can I access it in Java? How must the path look like?
You could open the directory and go over its contents until you find the file:
public static File getTextFileInDirectory(String dirPath) {
File dir = new File(dirPath);
for (File f : dir.listFiles()) {
if (f.isFile() && f.getName().endsWith(".txt")) {
return f;
}
}
return null;
}
EDIT:
Based on the comments below, if it's safe to assume the directory always has a file in it, and there's nothing else in the directory (e.g., subdirectories), this code can be greatly simplified:
public static File getTextFileInDirectory(String dirPath) {
return new File(dirPath).listFiles()[0];
}
Since you know there will only be one file in the directory, you can get an array of the directory's files and return the first element if it exists, or null if it doesn't.
public static File getFileFromDir(File directory) {
File[] dirFiles = directory.listFiles();
return dirFiles.length > 0 ? dirFiles[0] : null;
}

Categories