I have used this reference to read a file on my project. but i need to store likewise i don't know how to do this? please help me.
for reading a file i have taken the code from the link
InputStream csv =
SomeClassInTheSamePackage.class.getResourceAsStream("filename.csv");
Like this can anyone help me with writing a file
currently I'm using this code:
Writer output = null;
output = new BufferedWriter(new FileWriter("./filename.csv"));
But it throws FileNotFound Exception at runtime
Issue is with locating file path. it works fine if i give absolute path. but it needs to be run in any computer
The FileWriter will create files as required. It doesn't have to exist already.
The only way you can get this error is if the current working directory no longer exists or you don't have permission to create a file in the directory.
Check your permissions:
Writer output = null;
if (new File("./filename.csv").canWrite()) {
System.out.println("You have not permissions");
} else {
output = new BufferedWriter(new FileWriter("./filename.csv"));
...
}
OK..Use the following code to get the path of file:
String path = System.getProperty("user.dir");
FileWriter fw = new FileWriter(path+File.separator+"filename.csv");
EDIT
Here is a Demo Code that is creating file "pqr.txt" in package myPackage. Given that I am executing the class file using command java myPackage.AccessCheck i.e from one directory above the mypackage.
package myPackage;
import java.io.FileWriter;
import java.io.File;
public class AccessCheck
{
protected void callme()
{
try
{
String name = System.getProperty("user.dir")+File.separator+AccessCheck.class.getPackage().getName()+File.separator+"pqr.txt";
System.out.println(name);
FileWriter fw = new FileWriter(name);
}catch(Exception ex){ex.printStackTrace();}
}
public static void main(String st[])
{
AccessCheck asc = new AccessCheck();
asc.callme();
}
}
Instead of calling getResourceAsStream(), call class.getResource() or classLoader.getResource(). These functions return a URL giving the location of the resource. If the resource is a plain file on the filesystem, the URL will be a file: URL.
Once you have the URL, you can convert it to a URI and pass it to the File constructor which takes a URI. Then you can use the File object to open the file.
Note that getResource() can return URLs that the File constructor can't deal with. For example, if the resource is found in a jar file, then the URL might look like this:
jar:file:/C:/path/to/JDK/lib/vm.jar!/java/lang/Object.class
The File constructor can't deal with URLs like this. This may or may not be a concern for you.
Related
I'm trying to define a File in Java with a txt file called "helloworld". I've placed this file in a resources folder and when making the file I defined it like this:
File file = new File("/helloworld");
However I get this error when compiling
Exception in thread "main" java.io.FileNotFoundException: /helloworld
(No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileReader.<init>(FileReader.java:72)
at Tests.main(Tests.java:15)
This is the entire code I am trying to execute if that helps troubleshoot this issue
// Java Program to illustrate reading from FileReader
// using BufferedReader
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.net.URL;
public class Tests
{
public static void main(String[] args)throws Exception
{
File file = new File("/helloworld");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null)
System.out.println(st);
}
}
Thank you for the help!
public File(String pathname)
Creates a new File instance by converting the given pathname string
into an abstract pathname. If the given string is the empty string,
then the result is the empty abstract pathname.
You are trying to create a new File instance but the file called helloworld is not found or some other reasons. That's why you get the error,
Exception in thread "main" java.io.FileNotFoundException: /helloworld
The named file does not exist.
The named file is actually a directory.
The named file cannot be opened for reading for some reason.
You say that you try to define a file but your code seems to read. Try below one if you want to create a file,
import java.io.*;
import java.nio.charset.StandardCharsets;
class TestDir {
public static void main(String[] args) {
String fileName = "filename.txt";
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileName), StandardCharsets.UTF_8))) {
writer.write("write something in text file");
} catch (IOException e) {
e.printStackTrace();
}
}
}
It is easy to diagnose: The path you specified starts with a slash, so it means that the file is expected to be located at the root directory of the filesystem. You'd better strip off the leading slash, and:
Either start your program at the same directory the file is at.
Either specify an absolute/relative path in your code when instantiating the File object.
If the file is in a resources folder and is intended to be bundled with your program, you need to treat it like a resource, not a file.
This means you should not use the File class. You should read your data with the Class.getResource or Class.getResourceAsStream method:
BufferedReader br = new BufferedReader(
new InputStreamReader(
Tests.class.getResourceAsStream("/helloworld")));
This becomes especially important if you want to distribute a program as a .jar file. A .jar file is a compressed archive (actually a zip file with different extension) which contains both compiled class files and resources. Since they are all compressed into one .jar file, they are not individual files at all, so there is no way the File class can refer to them.
Although the File class is not useful for what you’re trying to do, you may want to research the concept of absolute file names and relative file names. By starting a file name with /, you are specifying an absolute file name, which means you are telling the program to look for the file in a specific place—a place where the file almost certain will not reside.
Try bellow to know where is the folder or file's path, which your program is looking for
System.out.println(file.getAbsolutePath());
With
File file = new File("/helloworld");
I think your program is looking for c:\helloworld, and there is no file or folder's name is helloword in your C drive
If you put the helloword.txt into C drive, and
File file = new File("C:\\helloworld.txt");
FileNotFoundException will disappear.
I have an excel file which I have kept in a subfolder of my main package.
I want to read that file. When I read it using InputStream, it file is easily detected but when I read using FileInputStram or File file = new File(filepath) I get the error that the file is not found.
Can anyone help me in reading the file using FileInputStram or File file = new File(filepath)?
The code what I wrote to read the file is
File file = new File("upgradeworkbench/Resources/workbookOut.xlsm");
and
FileInputStream inp = new FileInputStream("upgradeworkbench/Resources/workbookOut.xlsm");
I tried with / in the beginning of the path but still it didn't work.
When working with File class you need to provide either absolute or relative path. Absolute path is the full file path e.g. C:\workbookOut.xlsm
In relative paths, there is a concept of a working directory and it's represented by a . (dot) and everything else is relative to it.
Try either giving the full path or the relative path.
File file = new File("./upgradeworkbench/Resources/workbookOut.xlsm");
If your file in classpath then try below code
package mypack;
import java.io.*;
public class TestPath
{
public static void main(String[] args) throws Exception
{
InputStream stream = Test.class.getResourceAsStream("/workbookOut.xlsm");
System.out.println(stream != null);
stream = Test.class.getClassLoader()
.getResourceAsStream("workbookOut.xlsm");
System.out.println(stream != null);
}
}
If your file in same package then use the below line it will work
URL url = getClass().getResource("workbookOut.xlsm");
File file =new File(url.getPath());
I am creating a file like this (I am sending arg[0] as the name of the file to be created).
No file is created I searched through the source of the project and found nothing, why?
import java.io.File;
public class Test {
public static void main (String [] args)
{
File f=new File(args[0]);
}
}
Try with
File f=new File(args[0]);
f.createNewFile();
File is just a representation of the path. You need to actually open an output stream with that file and write to that for a file to be created.
This is normal.
A File is an abstract object. It may, or may not, refer to an existing resource on the filesystem.
But since this is 2015, drop File, use java.nio.file instead:
final Path path = Paths.get(args[0]);
Files.createFile(path);
But really, you shouldn't use File in 2015. Seriously. Yes, .createNewFile() exists on File but... Well, read the page. In short: returns a boolean, need to check the return value, if false, SOL, you can't even diagnose.
Edit: a page to learn how to use java.nio.file: here
(shameless self-advertising for both links, sorry for that)
Just creating file object does not create physical file on disk.Actual file is created with f.createNewFile() as explained in below demo
When yo do File file=new File(args[0]); file just represents the java object not the file object on file system
Here is demo for basic file create and delete operations
public class FileDemo {
public static void main(String[] args) {
File f = null;
try{
// create new file
f = new File("test.txt");
// tries to create new file in the system
f.createNewFile();
// deletes file from the system
f.delete();
}catch(Exception e){
e.printStackTrace();
}
}
}
Executing new File(...) does not create a file in the file system. A File object is just a way of representing the path for a file system object that may or may not existing.
The typical way to create a file is to open a FileOutputStream or FileWriter for the file. The file is created even if you don't write anything. Other alternatives are to call File.createNewFile() or File.createTempFile(...).
I would like to write to a .txt file that is inside a package. I can get it to read from the exact location the .txt file is stored but not from inside the package. I'm assuming it is using class loaders but I cannot seem to get it to work.
Here is what I have so far.
public void writeFile(String fileLocation) {
Writer output = null;
File file = new File(fileLocation);
try {
output = new BufferedWriter(new FileWriter(file));
output.append("WRITING TEST");
output.close();
} catch (IOException ex) {
System.out.println("Couldn't write to file.");
}
}
Then I use this in another class to write.
WriteFile writeFile = new WriteFile();
writeFile.writeFile("src/com/game/scores.txt");
I understand that if using class loaders you remove "src/" because that will no longer exist when the program is compiled in a .jar.
It is not possible to write or update a file inside jar. Since jar itself is a file.
Please refer this link.
Write To File Method In JAR
You could use a class in that package to give you the location of the folder.
Try something like
public URL getPackageLocation() {
return getClass().getResource(".");
}
This should give you the location of the folder from which this method is being called from.
From the comments you already know that you cann't write to a file, which resides in a JAR file. At best what you can do, is creating your file, relative to the path where the JAR is located like bellow:
mylocation
|-- my-jar.jar
|-- com
|--game
|--myfile.txt
I would like to write to it to update the scores in my game as the
user goes through the levels.
While it might be possible to write to the JAR file, I don't recommend it for this use case. Just write it somewhere at:
Path userdir = Paths.get(System.getProperty("user.home"), ".myApp", "<my app version>");
You can't write into Jar file. Writing into Jar file is not recommendable. You can write outside the jar file.
Please refer this and this stack overflow question for more details.
I have a project with 2 packages:
tkorg.idrs.core.searchengines
tkorg.idrs.core.searchengines
In package (2) I have a text file ListStopWords.txt, in package (1) I have a class FileLoadder. Here is code in FileLoader:
File file = new File("properties\\files\\ListStopWords.txt");
But I have this error:
The system cannot find the path specified
Can you give a solution to fix it?
If it's already in the classpath, then just obtain it from the classpath instead of from the disk file system. Don't fiddle with relative paths in java.io.File. They are dependent on the current working directory over which you have totally no control from inside the Java code.
Assuming that ListStopWords.txt is in the same package as your FileLoader class, then do:
URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.getPath());
Or if all you're ultimately after is actually an InputStream of it:
InputStream input = getClass().getResourceAsStream("ListStopWords.txt");
This is certainly preferred over creating a new File() because the url may not necessarily represent a disk file system path, but it could also represent virtual file system path (which may happen when the JAR is expanded into memory instead of into a temp folder on disk file system) or even a network path which are both not per definition digestable by File constructor.
If the file is -as the package name hints- is actually a fullworthy properties file (containing key=value lines) with just the "wrong" extension, then you could feed the InputStream immediately to the load() method.
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("ListStopWords.txt"));
Note: when you're trying to access it from inside static context, then use FileLoader.class (or whatever YourClass.class) instead of getClass() in above examples.
The relative path works in Java using the . specifier.
. means same folder as the currently running context.
.. means the parent folder of the currently running context.
So the question is how do you know the path where the Java is currently looking?
Do a small experiment
File directory = new File("./");
System.out.println(directory.getAbsolutePath());
Observe the output, you will come to know the current directory where Java is looking. From there, simply use the ./ specifier to locate your file.
For example if the output is
G:\JAVA8Ws\MyProject\content.
and your file is present in the folder "MyProject" simply use
File resourceFile = new File("../myFile.txt");
Hope this helps.
The following line can be used if we want to specify the relative path of the file.
File file = new File("./properties/files/ListStopWords.txt");
InputStream in = FileLoader.class.getResourceAsStream("<relative path from this class to the file to be read>");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
try .\properties\files\ListStopWords.txt
I could have commented but I have less rep for that.
Samrat's answer did the job for me. It's better to see the current directory path through the following code.
File directory = new File("./");
System.out.println(directory.getAbsolutePath());
I simply used it to rectify an issue I was facing in my project. Be sure to use ./ to back to the parent directory of the current directory.
./test/conf/appProperties/keystore
While the answer provided by BalusC works for this case, it will break when the file path contains spaces because in a URL, these are being converted to %20 which is not a valid file name. If you construct the File object using a URI rather than a String, whitespaces will be handled correctly:
URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.toURI());
Assuming you want to read from resources directory in FileSystem class.
String file = "dummy.txt";
var path = Paths.get("src/com/company/fs/resources/", file);
System.out.println(path);
System.out.println(Files.readString(path));
Note: Leading . is not needed.
I wanted to parse 'command.json' inside src/main//js/Simulator.java. For that I copied json file in src folder and gave the absolute path like this :
Object obj = parser.parse(new FileReader("./src/command.json"));
For me actually the problem is the File object's class path is from <project folder path> or ./src, so use File file = new File("./src/xxx.txt"); solved my problem
For me it worked with -
String token = "";
File fileName = new File("filename.txt").getAbsoluteFile();
Scanner inFile = null;
try {
inFile = new Scanner(fileName);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while( inFile.hasNext() )
{
String temp = inFile.next( );
token = token + temp;
}
inFile.close();
System.out.println("file contents" +token);
If text file is not being read, try using a more closer absolute path (if you wish
you could use complete absolute path,) like this:
FileInputStream fin=new FileInputStream("\\Dash\\src\\RS\\Test.txt");
assume that the absolute path is:
C:\\Folder1\\Folder2\\Dash\\src\\RS\\Test.txt
String basePath = new File("myFile.txt").getAbsolutePath();
this basepath you can use as the correct path of your file
if you want to load property file from resources folder which is available inside src folder, use this
String resourceFile = "resources/db.properties";
InputStream resourceStream = ClassLoader.getSystemClassLoader().getResourceAsStream(resourceFile);
Properties p=new Properties();
p.load(resourceStream);
System.out.println(p.getProperty("db"));
db.properties files contains key and value db=sybase
If you are trying to call getClass() from Static method or static block, the you can do the following way.
You can call getClass() on the Properties object you are loading into.
public static Properties pathProperties = null;
static {
pathProperties = new Properties();
String pathPropertiesFile = "/file.xml";
// Now go for getClass() method
InputStream paths = pathProperties.getClass().getResourceAsStream(pathPropertiesFile);
}