Reading files from outside the class path in Intellij - java

I am trying to read a file given its path that may not be inside the class path of the current project; the project has been exported as a separate .jar file and should be run from any directory it is located in. The code for reading the file is:
try {
FileInputStream fstream = new FileInputStream(inputFile);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = bufferedReader.readLine()) != null) {
// read file
bufferedReader.close();
} catch (IOException e) {
System.out.println("Err couldn't find " + inputMailFile);
}
This question only refers to the case when a file is being read from the current working directory.
How can I read a file given only its path?
inputFile is a string to the file path. For example:
C:\\Users\\user\\file.txt

Related

Read an already opened file in internet explorer without saving using java

When a file is opened in internet explorer without saving, it stores the file in temp folder. In windows 10 it creates a folder with random name in temp folder. I need to read the file using java. But java file api requires me to give the path of the file to read the contents of the file. How can I get the exact location of the file with the name that is stored by ie?
I tried using the java.io.tmpdir but it doesn't refer to the folder where the file is stored.
BufferedReader br = new BufferedReader(new FileReader(path to the file));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}
I expect exact file name and the path to the file location.

Error reading a txt file

I am getting this error in my code when trying to read a file saved on the external storage of my phone :
java.io.FileNotFoundException: shopping.txt: open failed: ENOENT (No such file or directory)
I can manage to write data to this file with success, what I did a lot of times.
However, I cannot access for reading this same file, giving the entire path or through another method.
The code writing and saving successfully :
File path = new File(this.getFilesDir().getPath());
String value = "vegetables";
// File output = new File(path + File.separator + fileName);
File output = new File(getApplicationContext().getExternalFilesDir(null),"shopping.txt");
try {
FileOutputStream fileout = new FileOutputStream(output.getAbsolutePath());
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(value);
outputWriter.close();
//display file saved message
// Toast.makeText(getBaseContext(), "File saved successfully!",
// Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this,String.valueOf(output),Toast.LENGTH_LONG).show();
Log.d("MainActivity", "Chemin fichier = [" + output + "]");
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
The writing piece of code crashing my app :
try
{
File gFile;
FileInputStream fis = new FileInputStream (new File("shopping.txt"));
//FileInputStream fis = openFileInput("/storage/emulated/0/Android/data/com.example.namour.shoppinglist/files/shopping.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line = null, input="";
while ((line = reader.readLine()) != null)
input += line;
Toast.makeText(MainActivity.this,line,Toast.LENGTH_LONG).show();
reader.close();
fis.close();
Toast.makeText(MainActivity.this,"Read successful",Toast.LENGTH_LONG).show();
//return input;
}
catch (IOException e)
{
Log.e("Exception", "File read failed: " + e.toString());
//toast("Error loading file: " + ex.getLocalizedMessage());
}
What am I doing wrong ?
For sure, not a problem of permissions, since I can write with success.
Many thanks for your help.
You missed to specifiy the correct path. You are looking for a file named shopping.txt in your current working directory (at runtime).
Create a new File object with the correct path and it will work:
File input = new File(getApplicationContext().getExternalFilesDir(null),"shopping.txt");. You could reuse your object from writing.
While opening the file, you are simply using new File("shopping.txt").
You need to specify the parent folder, like this:
new File(getExternalFilesDir(),"shopping.txt");
I recommend you make sure of org.apache.commons.io for IO, their FileUtils and FileNameUtils libs are great. ie: FileUtils.writeStringToFile(new File(path), data); Add this to gradle if you wish to use it: implementation 'org.apache.commons:commons-collections4:4.1'
In regards to your problem. When you write your file you are using:
getApplicationContext().getExternalFilesDir(null),"shopping.txt"
But when reading your file you are using:
FileInputStream fis = new FileInputStream (new File("shopping.txt"));
Notice that you didn't specify a path to shopping.txt simply the file name.
Why not do something like this instead:
//Get path to directory of your choice
public String GetStorageDirectoryPath()
{
String envPath = Environment.getExternalStorageDirectory().toString();
String path = FilenameUtils.concat(envPath, "WhateverDirYouWish");
return path;
}
//Concat filename with path
public String GetFilenameFullPath(String fileName){
return FilenameUtils.concat(GetStorageDirectoryPath(), fileName);
}
//Write
String fullFilePath = GetFilenameFullPath("shopping.txt");
FileUtils.writeStringToFile(new File(fullFilePath ), data);
//Read
File file = new File(fullFilePath);
StringBuilder text = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null){
text.append(line);
if(newLine)
text.append(System.getProperty("line.separator"));
}
br.close();

Cannot find file in netbeans + glassfish project

Here it is my folder project
I would like to read the file book-form.html which is in the directory web of my project and put it in a String.
This is how I call my function 'getFileContent':
String content = getFileContent("web/book-form.html");
And this is the function:
public String getFileContent(String filePath){
String line, content = new String();
try {
File file = new File(filePath);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while((line = br.readLine()) != null){
content += line;
}
br.close();
fr.close();
} catch(IOException e){
System.out.println(e.getMessage());
}
return content;
}
My problem is that netbeans tell me that it cannot find my file book-form.html
Any ideas ?
File path to resource in our war/WEB-INF folder?
Also you should close stream in a final block or use try-with-resource if you use jdk 7+
I find the way to do it:
Basically the program is in the main folder of Glassfish, so it's needed to put the entire path of your file from the root of your system to allow the program to find your file.

Is it possible to close the source File (file.close();) in java?

I am create a new file
File f = new File(file_path);
then the end of program can i possible to close that the file object or file?
f.close();
else there is a method is possible to close file??
public class etest2read {
public static void main(String[] args) throws IOException {
File dir = new File("input");
String source = dir.getCanonicalPath() + File.separator + "TestFile.txt";
//String TestFileone = dir.getCanonicalPath() + File.separator + "TestFileone.txt";
File fin = new File(source);
FileInputStream fis = new FileInputStream(fin);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
System.out.println("file/folder: "+fin.getAbsolutePath());
System.out.println("file/folder: "+dir.getCanonicalPath());
System.out.println("file/folder: "+fin.lastModified());
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
br.close();
System.out.println("Closed Buffered Reader");
fis.close();
System.out.println("Closed File Input Stream");
fin.close(); // providing the error
}
}
No it is not possible.
A File is an abstract representation of a file or directory pathname. You do not open the File, only a Stream or a Reader on that File.
No. You can only close the instances of objects that implement the Closeable interface (example Reader , InputStream etc). File class doesn't implement Closeable. Like Burkahard says, it is merely an abstract representation of the underlying file/ directory

Unable to add text file in java eclipse during creation of jar

I have created a java project in eclipse and added certain text files like follows
FileReader fin=null;
BufferedReader bin=null;
fin=new FileReader("src/main/resources/League.txt");
bin=new BufferedReader(fin);
But after creation of the ruunable jar or just simple jar when I run the jar file it is showing that no text file is found or the path is not found. But I have added the text files in the main.resource of my project. How to handle it?
Use URLClassLoader.getSystemResourceAsStream, this works in jars and in eclipse...
Make sure there's a file in the latest Java version directory src\main\resources\League.txt. For example, say for Windows, C:\Program Files\Java\jdk1.7.0_25\src\main\resources\League.txt.
You need to give front slashes, not back ones. Also, this should be the code:
FileReader fin=null;
BufferedReader bin=null;
fin=new FileReader("src\\main\\resources\\League.txt"); // Because of Unicode restrictions.
bin=new BufferedReader(fin);
Maybe you check this as well: How to get a path to a resource in a Java JAR file
Try this. Even though the file is in src/resources you need not say src folder in path.
BufferedReader br = null;
try {
String sCurrentLine;
URL url = ClassLoader.getSystemResource("resources/League.txt");
br = new BufferedReader(new InputStreamReader(url.openStream()));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}

Categories

Resources