Read/Write to a .txt file from JAR - java

Currently I'm developing a java application to carry out a survey. I want to read/write to a .txt file, creating a .csv to store inputted data. Below is code I have used so far to write data - Of course this makes the JAR file not portable as it has an absolute path.
File file = new File("C:/Files/JavaApp/src/text.text/");
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(file, true);
} catch (IOException e) {
System.out.println(e.getMessage());
}
bw = new BufferedWriter(fw);
try {
bw.write("blah" + ",");
} catch (IOException e) {
System.out.println(e.getMessage());
}
try {
bw.newLine();
} catch (IOException e) {
System.out.println(e.getMessage());
}
try {
bw.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
I have tried several methods such as ClassName.class.getResource("Text.text"); but it will always return a Reflection or a NullPointer error.
I know that writing to a file within the JAR does pose some problems, meaning I would have to point to a file outside to read/write. However I don't know how to preform this in code. I need the JAR file to be completely portable. Even if that means it must be kept within a directory, so the JAR can search for the .txt file within that directory. Or, is there another way?
If anyone can help me out, I would be very grateful.

To read from the Jar file: How to read a file from jar in Java?
The file is an archive file. It is a zip file with a .jar extension. You shouldn't be writing to it. If the jar file has been signed (security projected) you cannot write to it. Changing a single bit in the file will invalidate it.
What you should do is store a default file in Jar and load that to the "user.home" folder if it is not already there.

Related

FileNotFoundException: Creates child folder instead of file

I just started to work with files today with Android and have been pulling my hair out all day. This throws a FileNotFoundException:
public void writeConfig(){
try {
File file = new File(Environment.getExternalStorageDirectory() + "/" + "AppName", "TimetableConfiguration");
if (!file.mkdirs()) {
P.rint("Couldn't create directory");
}
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(getActivity().getSharedPreferences("periods", MODE_PRIVATE).getString("periods", null).getBytes());
fileOutputStream.close();
} catch (FileNotFoundException e) {
P.rint("Didn't find file");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Any ideas?
I notice that instead of creating a file, it creates a child folder. Why is it doing this?
Thanks for any help :)
FileNotFoundException: Creates child folder instead of file
Yes. That is what you do.
You first create with mkdirs() a directory with a certain name.
After that you try to create a file with the same name which is impossible as there cannot be two files or directories with the same name.
So have a look and you will find that directory.
Well you had deduced most all yourself already. Now try to understand your code.
if (!file.mkdirs()) {
P.rint("Couldn't create directory");
You will see that printed every time you repeat the code. You should have seen this too. And have told us.
You should only call mkdirs if the directory does not exist yet.

Creating temporary file and rename to actual file

I am trying to create a temporary file and then rename it to a usable file. The temp file is getting created in %temp% but not getting renamed:-
static void writeFile() {
try {
File tempFile = File.createTempFile("TEMP_FAILED_MASTER", "");
PrintWriter pw = new PrintWriter(tempFile);
for (String record : new String[] {"a","b"}) {
pw.println(record);
}
pw.flush();
pw.close();
System.out.println(tempFile.getAbsolutePath());
File errFile = new File("C:/bar.txt");
tempFile.renameTo(errFile);
System.out.println(errFile.getAbsolutePath());
System.out.println("Check!");
} catch (Exception e) {
e.printStackTrace();
}
}
There are a few reasons why a rename can fail. The common ones are:
You don't have write permission for the source or destination directory.
The file you are renaming is open (on Windows)
You are attempting to rename across different file systems.
It can be difficult to diagnose these (and other) failure reasons if you are using File.renameTo because all you get is a boolean return value.
I recommend using Files.move instead. It can cope with moving files between file systems, and will throw an exception if the file cannot be renamed.

java Extracting Zip file

I'm looking for a way to extract Zip file. So far I have tried java.util.zip and org.apache.commons.compress, but both gave a corrupted output.
Basically, the input is a ZIP file contain one single .doc file.
java.util.zip: Output corrupted.
org.apache.commons.compress: Output blank file, but with 2 mb size.
So far only the commercial software like Winrar work perfectly. Is there a java library that make use of this?
This is my method using java.util library:
public void extractZipNative(File fileZip)
{
ZipInputStream zis;
StringBuilder sb;
try {
zis = new ZipInputStream(new FileInputStream(fileZip));
ZipEntry ze = zis.getNextEntry();
byte[] buffer = new byte[(int) ze.getSize()];
FileOutputStream fos = new FileOutputStream(this.tempFolderPath+ze.getName());
int len;
while ((len=zis.read(buffer))>0)
{
fos.write(buffer);
}
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally
{
if (zis!=null)
{
try { zis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Many thanks,
Mike
I think your input may be compressed by some "incompatible" zip program like 7zip.
Try investigating first if it can be unpacked with a classical WinZip or such.
Javas zip handling is very well able to deal with zipped archives that come from a "compatible" zip compressor.
It is an error in my code. I need to specify the offset and len of bytes write.
it works for me
ZipFile Vanilla = new ZipFile(new File("Vanilla.zip")); //zipfile defined and needs to be in directory
Enumeration<? extends ZipEntry> entries = Vanilla.entries();// all (files)entries of zip file
while(entries.hasMoreElements()){//runs while there is files in zip
ZipEntry entry = entries.nextElement();//gets name of file in zip
File folderw =new File("tkwgter5834");//creates new directory
InputStream stream = Vanilla.getInputStream(entry);//gets input
FileInputStream inpure= new FileInputStream("Vanilla.zip");//file input stream for zip file to read bytes of file
FileOutputStream outter = new FileOutputStream(new File(folderw +"//"+ entry.toString())); //fileoutput stream creates file inside defined directory(folderw variable) by file's name
outter.write(inpure.readAllBytes());// write into files which were created
outter.close();//closes fileoutput stream
}
Have you tried jUnrar? Perhaps it might work:
https://github.com/edmund-wagner/junrar
If that doesn't work either, I guess your archive is corrupted in some way.
If you know the environment that you're going to be running this code in, I think you're much better off just making a call to the system to unzip it for you. It will be way faster than anything that you implement in java.
I wrote the code to extract a zip file with nested directories and it ran slowly and took a lot of CPU. I wound up replacing it with this:
Runtime.getRuntime().exec(String.format("unzip %s -d %s", archive.getAbsolutePath(), basePath));
That works a lot better.

FileNotFoundException when using FileWriter

I am trying to write some message to text file. The text file is in the server path. I am able to read content from that file. But i am unable to write content to that file. I am getting FileNotFoundException: \wastServer\apps\LogPath\message.txt (Access Denied).
Note: File has a read and write permissions.
But where i am doing wrong. Please find my code below.
Code:
String FilePath = "\\\\wastServer\\apps\\LogPath\\message.txt";
try {
File fo = new File(FilePath);
FileWriter fw=new FileWriter(fo);
BufferedWriter bw=new BufferedWriter(fw);
bw.write("Hello World");
bw.flush();
bw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Please help me on this?
Please check whether you can access the apps and LogPath directory.
Type these on Run (Windows Key + R)
\\\\wastServer\\apps\\
\\\\wastServer\\apps\\LogPath\\
And see whether you can access those directories from the machine and user you are executing the above code.
You don't have write access to the share, one of the directories, or the file itself. Possibly the file is already open.
After this line
File fo = new File(FilePath);
try to print the absolute path
System.out.println( fo.getAbsolutePath() );
And then check whether the file exists in that location, instead of directly checking at
\\\\wastServer\\apps\\LogPath\\message.txt
So , you will know, where the compiler is searching for the file.

Java: Error when save file in Resource after Deployment

My program has a function that read/write file from resource. This function I have tested smoothly.
For example, I write something to file, restart and loading again, I can read that data again.
But after I export to jar file, I faced problems when write file. Here is my code to write file:
URL resourceUrl = getClass().getResource("/resource/data.sav");
File file = new File(resourceUrl.toURI());
FileOutputStream output = new FileOutputStream(file);
ObjectOutputStream writer = new ObjectOutputStream( output);
When this code run, I has notice error in Command Prompt:
So, My data cannot saved. (I know it because after I restarted app, nothing changed !!!)
Please help me solve this problem.
Thanks :)
You simply can't write files into a jar file this way. The URI you get from getResource() isn't a file:/// URI, and it can't be passed to java.io.File's constructor. The only way to write a zip file is by using the classes in java.util.zip that are designed for this purpose, and those classes are designed to let you write entire jar files, not stream data to a single file inside of one. In a real installation, the user may not even have permission to write to the jar file, anyway.
You're going to need to save your data into a real file on the file system, or possibly, if it's small enough, by using the preferences API.
You need to read/write file as an input stream to read from jar file.
public static String getValue(String key)
{
String _value = null;
try
{
InputStream loadedFile = ConfigReader.class.getClassLoader().getResourceAsStream(configFileName);
if(loadedFile == null) throw new Exception("Error: Could not load the file as a stream!");
props.load(loadedFile);
}
catch(Exception ex){
try {
System.out.println(ex.getMessage());
props.load(new FileInputStream(configFileName));
} catch (FileNotFoundException e) {
ExceptionWriter.LogException(e);
} catch (IOException e) {
ExceptionWriter.LogException(e);
}
}
_value = props.getProperty(key);
if(_value == null || _value.equals("")) System.out.println("Null value supplied for key: "+key);
return _value;
}

Categories