Not able to access file in eclipse gives : FileNotFoundException - java

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.

Related

Cannot Access Folder in 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.
}
}
}

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));
}
}
}
}

How to hide existing folder in Android?

I have a existing folder (Old Folder name : xyz) in Sdcard, Whenever I try to rename this folder (New Folder name : .xyz) using toRename(). It return false and create a new folder (name : .xyz). Old Folder (name : xyz) is also visible in sdcard.
How to rename the existing folder to make a that Folder hidden in Android?
String dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/xyz";
File file = new File(dir);
StringdirHide = Environment.getExternalStorageDirectory().getAbsolutePath() + "/.xyz";
File fileHide = new File(dirHide);
if (!file.exists() && !fileHide.exists())
{
fileHide.mkdir();
}
else if(file.exists())
{
file.toRename(fileHide);
}
The method to rename is renameTo. The following code should work. Tell me if you face any problems.
String dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/xyz";
File file = new File(dir);
String dirHide = Environment.getExternalStorageDirectory().getAbsolutePath() + "/.xyz";
File fileHide = new File(dirHide);
if (file.exists() && !fileHide.exists()) {
file.renameTo(fileHide);
} else if(!file.exists()) {
fileHide.mkdir();
}
#Akashsingla19 I think problem is the folder u want to rename is not exist run following code Twice hope you will get your answer
if (!file.exists())
{
file.mkdir();
}
else if(file.exists())
{
file.renameTo(fileHide);
}
In your code you are using some toRename() method, which i couldn't found anywhere in File class in android. Actual method of File class in android to rename folders and files is renameTo(). Check this method and try to use it and revert please.
Thanks.

How to create a directory using File.getParentFile().getName() with relative path

I am having an input folder say c:\files\input\ that contains my list of files that I am using.
How do I use the above to create say c:\files\output\ and copy the files from the input folder to the output folder?
My c:\files\input is read from an object, say
String inputFolder = dataMap.getString("folder");// this will get c:\files\input\
You got path of folder in variable inputFolder now do as follows.
String inputFolder = dataMap.getString("folder");
File dir = new File(inputFolder);
if(dir.mkdirs()){
System.out.println("Directory created");
}else{
System.out.println("Directory Not Created");
}
You can use FileUtils from org.apache.commons.io library
FileUtils.copyDirectory(srcDir, destDir);
so in your case:
File file = new File(inputFolder);
String parentDir = file.getParentFile().getAbsolutePath();
File outputDir = new File(parentDir, "output");
if(!outputDir.exsit()) {
outputDir.mkdir();
}
FileUtils.copyDirectory(inputFolder, outputDir);
To Create the directory you can refer to the below code
File file = new File("c:\\files\\output");
if (!file.exists()) {
if (file.mkdir()) {
System.out.println("Directory is created!");
} else {
System.out.println("Failed to create directory!");
}
}
To copy files from a directory to another directory.. refer to the following link it gives a good explanation with source code examples
http://examples.javacodegeeks.com/core-java/io/file/4-ways-to-copy-file-in-java/

Java, reading a file from current directory?

I want a java program that reads a user specified filename from the current directory (the same directory where the .class file is run).
In other words, if the user specifies the file name to be "myFile.txt", and that file is already in the current directory:
reader = new BufferedReader(new FileReader("myFile.txt"));
does not work. Why?
I'm running it in windows.
Try
System.getProperty("user.dir")
It returns the current working directory.
The current directory is not (necessarily) the directory the .class file is in. It's working directory of the process. (ie: the directory you were in when you started the JVM)
You can load files from the same directory* as the .class file with getResourceAsStream(). That'll give you an InputStream which you can convert to a Reader with InputStreamReader.
*Note that this "directory" may actually be a jar file, depending on where the class was loaded from.
None of the above answer works for me. Here is what works for me.
Let's say your class name is Foo.java, to access to the myFile.txt in the same folder as Foo.java, use this code:
URL path = Foo.class.getResource("myFile.txt");
File f = new File(path.getFile());
reader = new BufferedReader(new FileReader(f));
Files in your project are available to you relative to your src folder. if you know which package or folder myfile.txt will be in, say it is in
----src
--------package1
------------myfile.txt
------------Prog.java
you can specify its path as "src/package1/myfile.txt" from Prog.java
If you know your file will live where your classes are, that directory will be on your classpath. In that case, you can be sure that this solution will solve your problem:
URL path = ClassLoader.getSystemResource("myFile.txt");
if(path==null) {
//The file was not found, insert error handling here
}
File f = new File(path.toURI());
reader = new BufferedReader(new FileReader(f));
Thanks #Laurence Gonsalves your answer helped me a lot.
your current directory will working directory of proccess so you have to give full path start from your src directory like mentioned below:
public class Run {
public static void main(String[] args) {
File inputFile = new File("./src/main/java/input.txt");
try {
Scanner reader = new Scanner(inputFile);
while (reader.hasNextLine()) {
String data = reader.nextLine();
System.out.println(data);
}
reader.close();
} catch (FileNotFoundException e) {
System.out.println("scanner error");
e.printStackTrace();
}
}
}
While my input.txt file is in same directory.
Try this:
BufferedReader br = new BufferedReader(new FileReader("java_module_name/src/file_name.txt"));
try using "."
E.g.
File currentDirectory = new File(".");
This worked for me

Categories