Write to a .txt file in a package - java

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.

Related

Java create a folder in current package folder

In my java program, I want to write files to a folder inside my current package. If this folder doesn't exist, I will create it.
How do I refer to this maybe non-existent folder with relative path, so that if I move my package around, I don't have to manually fix the path?
private void writeFamilyPerFile(String name, ArrayList<String> planNames) {
File file;
File folder = new File(OUTPUT_DIR + "/temp/");
BufferedWriter bw = null;
try {
if(!folder.exists()) {
folder.mkdir();
}
file = new File(folder + name + ".md");
file.createNewFile();
bw = new BufferedWriter(planNames);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bw != null) {
try {
bw.close();
} catch (IOException ignore) {
}
}
}
}
OUTPUT_DIR is the path to my current package, and folder is the folder I want to create inside current package directory.
UPDATE
Thanks everyone for answering my question. I'm not very experienced, so is making a lot mistakes.
I'm generating a bunch of markdown files, which could be used as is, and will be processed further later in my app, i.e., merged into 1 single file, and translated into HTML. My app lives inside a project, the file structure is like this:
root
|--other parts
|--definitions
| |--definition
| |--java
| | |--validator
| | |--docGenerator
| |--pom.xml
|--pom.xml
docGenerator is my project. Where should I put:
intermediate generated files, which I'd like to keep
temp files I will generated, use and delete
final output files
resource files my program read and use
Big thanks to everyone!
Well assuming your current path is within the application folder (where your package folders are), and your class files are not within a jar, you can do this.
String OUTPUT_DIR = this.getClass().getCanonicalName().replace(".","/");
OUTPUT_DIR = OUTPUT_DIR.substring(0,OUTPUT_DIR.lastindexOf('/'));
It is very unclear from your Question what you are trying to do. However, I think that this is what you are asking for:
...
File outputDir = new File(OUTPUT_DIR);
File outputFile = new File(outputDir, planNames.get(i) + ".md");
bw = new BufferedWriter(new FileWriter(outputFile));
...
The above opens a file (named planNames.get(i) + ".md") in the directory OUTPUT_DIR. The file is opened for writing as a text file. It will be created if it doesn't exist already, and truncated if it does exist.
This assumes that the output directory already exists, and that OUTPUT_DIR is a String whose value is a resolvable pathname for the directory.
I should also point out that writing files into the project source tree in your IDE is not going to work if your application even needs to run outside of an IDE. (And this is a strange thing to do inside an IDE too ... unless you are generating Java source code.)
In that sense, you are probably asking for the wrong thing; i.e. something that doesn't make sense. If you told us what you are actually trying to do here, we could suggest alternatives that made more sense.

Relative path to store a file in any computer - Java

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.

Reading a text file in my .jar

Lets say I'm making a program that needs to copy all the lines in a .txt file within my .jar file. it is in the package program.files and it is named text.txt. I've been looking all over the internet, and i cant find what I'm looking for. i think that this idea:
public String readSpecificFromJar(String dir, int line) {
String read = null;
try {
InputStream in = getClass().getResourceAsStream(dir);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(in));
/**
* declare string variable and prime the read
*/
read = bufferedReader.readLine();
for (int i = 1; i < line; i++) {
read = bufferedReader.readLine();
}
bufferedReader.close();
} catch (IOException ioexception) {
Dialogs.fail("Could not read txt file from the JAR!!! Error Code: 06");
}
return read;
}
would work, but i tried that and it gave me all kinds of errors. what i think the problem would be is declaring the InputStream in the way it does it want the file to be right there with the Main method. how would i change this so it is not the case? thanks in advance!
EDIT:
due to some confusion, i want to clear this up. for the String dir i am entering files/text.txt. it wont work. how do i fix this?
EDIT 2:
OK i feel like the problem isn't getting across, and I'm kinda getting aggravated, mainly because I'm pretty tired. the code that WORKS for a different program is up above, where the dir is simply "text.txt"
THIS DOESN'T WORK FOR WHAT I'M DOING AND IM NOT SURE WHY. again, the file is IN THE CLASSPATH so dir is only "text.txt". I want my .txt file to be "files/text.txt". How do i do this?
EDIT 3:
I dont know if i mentioned it, but my .txt file is INSIDE my jar. just to clear up the confusion. so really, the path of the .jar file shouldn't matter, as in I shouldn't have to type it in with the dir. also, the main class is in the package main and the .txt file is in the package files all within the same program named copy. also, i tried moving the txt file to the same package as the main class, also didn't work.
EDIT 4:
by the way, the package that holds the method for reading from the jar is IO. as in the class io is inside the package IO. all of my files such as images and txt are in the package files. just thought id clear that up. i tried moving the txt file to the package of the io class, and that worked, but if its in any other package, even if i include the package name in the dir it wont work. any ideas as to why?
The .txt file should be in The root directory of dir is the same directory where your class file is located in.
EDIT: due to some confusion, i want to clear this up. for the String
dir i am entering files/text.txt. it wont work. how do i fix this?
What is the path of the class? (the class that contains readSpecificFromJar()) If the .class file and the .txt file are both in the same directory, then you should make it like this:
dir = "text.txt";
EDIT 4: by the way, the package that holds the method for reading from
the jar is IO. as in the class io is inside the package IO. all of my
files such as images and txt are in the package files. just thought id
clear that up. i tried moving the txt file to the package of the io
class, and that worked, but if its in any other package, even if i
include the package name in the dir it wont work. any ideas as to why?
Try this:
dir = "../files/text.txt";
I believe this would work if your structure is as follows:
javaApp.jar
|
_____|_____
| |
files IO
| |
| |
text.txt io.class

Reading .txt file from another directory

The code I am running is in /Test1/Example. If I need to read a .txt file in /Test1 how do I get Java to go back 1 level in the directory tree, and then read my .txt file
I have searched/googled and have not been able to find a way to read files in a different location.
I am running a java script in an .htm file located at /Test1/Test2/testing.htm. Where it says script src=" ". What would I put in the quotations to have it read from my file located at /Test1/example.txt.
In Java you can use getParentFile() to traverse up the tree. So you started your program in /Test1/Example directory. And you want to write your new file as /Test1/Example.txt
File currentDir = new File(".");
File parentDir = currentDir.getParentFile();
File newFile = new File(parentDir,"Example.txt");;
Obviously there are multiple ways to do this.
You should be able to use the parent directory reference of "../"
You may need to do checks on the OS to determine which directory separation you should be using ['\' compared to '/']
When you create a File object in Java, you can give it a pathname. You can either use an absolute pathname or a relative one. Using absolutes to do what you want would require:
File file = new File("/Test1/myFile.txt");
if(file.canRead())
{
// read file here
}
Using relatives paths if you want to run from the location /Test1/Example:
File file = new File("../myFile.txt");
if(file.canRead())
{
// read file here
}
I had a similar experience.
My requirement is: I have a file named "sample.json" under a directory "input", I have my java file named "JsonRead.java" under a directory "testcase". So, the entire folder structure will be like untitled/splunkAutomation/src and under this I have folders input, testcase.
once after you compile your program, you can see a input file copy named "sample.json" under a folder named "out/production/yourparentfolderabovesrc/input" and class file named "JsonRead.class" under a folder named "out/production/yourparentfolderabovesrc/testcase". So, during run time, Java will actually refer these files and NOT our actual .java file under "src".
So, my JsonRead.java looked like this,
package testcase;
import java.io.*;
import org.json.simple.JSONObject;
public class JsonRead{
public static void main(String[] args){
java.net.URL fileURL=JsonRead.class.getClass().getResource("/input/sample.json");
System.out.println("fileURL: "+fileURL);
File f = new File(fileURL.toURI());
System.out.println("fileIs: "+f);
}
}
This will give you the output like,
fileURL: file:/C:/Users/asanthal/untitled/out/production/splunkAutomation/input/sample.json
fileIs: C:\Users\asanthal\untitled\out\production\splunkAutomation\input\sample.json
It worked for me. I was saving all my classes on a folder but I needed to read an input file from the parent directory of my classes folder. This did the job.
String FileName = "Example.txt";
File parentDir = new File(".."); // New file (parent file ..)
File newFile = new File(parentDir,fileName); //open the file

How to pass a text file as a argument?

Im trying to write a program to read a text file through args but when i run it, it always says the file can't be found even though i placed it inside the same folder as the main.java that im running.
Does anyone know the solution to my problem or a better way of reading a text file?
Do not use relative paths in java.io.File.
It will become relative to the current working directory which is dependent on the way how you run the application which in turn is not controllable from inside your application. It will only lead to portability trouble. If you run it from inside Eclipse, the path will be relative to /path/to/eclipse/workspace/projectname. If you run it from inside command console, it will be relative to currently opened folder (even though when you run the code by absolute path!). If you run it by doubleclicking the JAR, it will be relative to the root folder of the JAR. If you run it in a webserver, it will be relative to the /path/to/webserver/binaries. Etcetera.
Always use absolute paths in java.io.File, no excuses.
For best portability and less headache with absolute paths, just place the file in a path covered by the runtime classpath (or add its path to the runtime classpath). This way you can get the file by Class#getResource() or its content by Class#getResourceAsStream(). If it's in the same folder (package) as your current class, then it's already in the classpath. To access it, just do:
public MyClass() {
URL url = getClass().getResource("filename.txt");
File file = new File(url.getPath());
InputStream input = new FileInputStream(file);
// ...
}
or
public MyClass() {
InputStream input = getClass().getResourceAsStream("filename.txt");
// ...
}
Try giving an absolute path to the filename.
Also, post the code so that we can see what exactly you're trying.
When you are opening a file with a relative file name in Java (and in general) it opens it relative to the working directory.
you can find the current working directory of your process using
String workindDir = new File(".").getAbsoultePath()
Make sure you are running your program from the correct directory (or change the file name so that it will be relative to where you are running it from).
If you're using Eclipse (or a similar IDE), the problem arises from the fact that your program is run from a few directories above where the actual source is located. Try moving your file up a level or two in the project tree.
Check out this question for more detail.
The simplest solution is to create a new file, then see where the output file is. That is the correct place to put your input file into.
If you put the file and the class working with it under same package can you use this:
Class A {
void readFile (String fileName) {
Url tmp = A.class.getResource (fileName);
// Or Url tmp = this.getClass().getResource (fileName);
File tmpFile = File (tmp);
if (tmpFile.exists())
System.out.print("I found the file.")
}
}
It will help if you read about classloaders.
say I have a text file input.txt which is located on the desktop
and input.txt has the following content
i came
i saw
i left
and below is the java code for reading that text file
public class ReadInputFromTextFile {
public static void main(String[] args) throws Exception
{
File file = new File(
"/Users/viveksingh/desktop/input.txt");
BufferedReader br
= new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null)
System.out.println(st);
}
}
output on the console:
i came
i saw
i left

Categories

Resources