Copying a binary file outside of a jar - java

I have an exe packaged inside my jar file and I am trying to copy it to a temporary location so that i can run it using Desktop.browse(), to do this I set up a scanner with the input stream constructor using class.getResourceAsStream, and then with a printwriter wrote that all to a file. The problem that occurred says that the exe is invalid. I think this is due to some binary data being lost. If anyone can help please post a comment.
Scanner sc = new Scanner(ClassBuilder.class.getResourceAsStream("jd-gui.exe"));
File copy = new File("C://users//Owner//Desktop//java//jd-gui.exe");
copy.createNewFile();
PrintWriter writer = new PrintWriter(copy);
while(sc.hasNextLine())
writer.println(sc.nextLine());
writer.flush();
writer.close();
sc.close();
Desktop.getDesktop().browse(copy.toURI());

As already mentioned use streams for binary data. Commons io makes copying streams easy. Something like:
InputStream in = getClass().getResourceAsStream("jd-gui.exe");
OutputStream out = new FileOutputStream("jd-gui.exe");
IOUtils.copy(in, out);

Related

In java, reading file using inputstream after deleting the file

I have a question regarding reading files in java.
Here is the sample code
File path = new File("myfile.txt");
InputStream inputStream = new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
file.delete();
String line;
while((line = reader.readLine()) != null) {
System.out.println(line);
}
I create an input stream and try to read it. As they say, its like a pipe, you read values byte by byte.
To speed it up, we can use BufferedReader which can read chunk by chunk.
So, I delete this file before reading.
Now, when i read it, it still reads complete file, even though file is not there.
If inputStream is a pipe, why is it not failing ? Any ideas ?
I'm pretty sure it's because the txt file you are loading from is so small it is fully read on initialization of the buffered reader.
In my opinion, the file still exists in the reader and the inputStream. Deleting the source file won't change anything until you rerun your application.
BufferedReader and InputStream classes are probaly prepared for similar situations like this. It can be useful if the source of the file goes offline during the run.
Correct me if I'm wrong, I'm not a professional programmer.

Java - Why does BufferedReader(Writer) create a corrupted excel(.xls), but BufferedInput(Output)Stream creates a good one

At the company I work, we have a job that retrieves emails, gets their attachments and saves them. Until now it only had to work with .xml and .txt files and it worked well.
We use the JavaMail 1.4.4 package. Existing code(modified to be more simpler. Don't mind the type checks):
Message message = ...;
MultiPart mp = (MultiPart)message.getContent();
File file = new File(newFileName);
Part part = mp.getBodyPart(indexWhereIsAttachement);
InputStream inputStream = part.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
//method that read all from reader and writes to writer
When I use a .xls file, it doesn't work. This creates a corrupted .xls file. I can't open it with LibreOffice, neither can I open it as a Apache WorkBook in code. But it works for .xml and .txt.
But if I do this:
...
File file = new File(newFileName);
Part part = mp.getBodyPart(indexWhereIsAttachement);
((MimeBodyPart)part).saveFile(file);
It works fine. Looking at the "saveFile()" method, it uses a BufferedInput(Output)Stream. So while reading the file, it doesn't convert the data to characters. Is this what's causing the issues? What exactly happens, that breaks everything?

Why is my attempt to append text to a file not responding?

I'm simply trying to add a new line of text to my *.txt file, but nothing happens at all. The file is packed with a .war, so I use a ClassLoader to access the file. Also, both my eclipse IDE, and the contents of the file, use UTF-8 encoding.
I've used these for inspiration:
How to add a new line of text to an existing file in Java?
Java BufferedWriter object with utf-8
Now my code is mainly based on the last post, and looks like this:
public class test {
public static void main(String[] args){
URL url = Thread.currentThread().getContextClassLoader().getResource("MilestoneExport.txt");
File file = new File(url.getFile());
System.out.println(file.canRead()); //true
System.out.println(file.canWrite()); //true
try {
BufferedWriter out = new BufferedWriter
(new OutputStreamWriter(new FileOutputStream(file),"UTF-8"));
out.append("new line");
out.append("new line 2");
out.append("new line 3");
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I've confirmed that the file is in fact found, and it reads fine. I've been able to output the entire content of it to the console through the use of a BufferedReader. The path of the file is also correct, but absolutely no text is added to the file. I've made sure that I have refreshed and updated every time I've run the program.
Also, I've tried to create a simple empty file called foo.txt, which is located in the same directory as test.java. I added the following code to the main method, as provided by the BufferedWriter API, at http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html
PrintWriter out2 = new PrintWriter(
new BufferedWriter(new FileWriter("foo.txt")));
out2.println("new Line");
out2.close();
What am i missing here? Why are there no error messages, and no responses or feedbacks whatsoever?
EVERYTHING BELOW IS ONLY ADDITIONAL INFO ABOUT WHAT I'VE TRIED. NO FEEDBACK IN ANY CASES:
Not this one: Why is BufferedWriter not writing to file?
Not this one: why is bufferedwriter not writing in the file?
Not this one: Unable to write to file using BufferedWriter
Yet another "remember to close/flush": Java : Problems accessing and writing to file
Defining the BufferedWriter outside the try block makes no difference, but I tried it anyway, due to How to write detail into file using BufferedWriter and FileWriter in Java?
Also, this code, from this answer, does nothing as well...
try {
BufferedWriter output = new BufferedWriter(new FileWriter(new File("house.txt")));
output.write("text");
output.close();
}
catch (IOException e) {
e.printStackTrace();
}
last but not least, I suspected that it might have something to do with the packaging of my Web-App, and differences between the source and target-folders. So I copied the code to a brand new clean project, but it still does nothing at all...
EDIT:
this code:
System.out.println(file.exists());
System.out.println(file.getAbsolutePath());
System.out.println(file.getCanonicalPath());
System.out.println(file.getName());
System.out.println(file.isDirectory());
System.out.println(file.isFile());
System.out.println(file.setLastModified(new GregorianCalendar().getTimeInMillis()));
gives these outputs:
true
D:\Data\myworkspace\MyProject\target\classes\MilestoneExport.txt
D:\Data\myworkspace\MyProject\target\classes\MilestoneExport.txt
MilestoneExport.txt
false
true
true
Am I completely misunderstanding the use of java's File-objects, and it's uses with FileWriters? The file is clearly 100% confirmed the correct file.
You should use the other constructor of FileOutputStream in order to open the file in append mode :
FileOutputStream(File file, boolean append)
I.e,
new FileOutputStream(file, true)
Since I can't comment, you might not be saving the file back into the archive it came from (I'm not sure if java supports writing to the internal structures of archives by editing the files that are included, however you might want to try to store the file externally to the archive to see if that is the place the issue comes from).
The cause of what you posted in the comments is that your IDE won't extract the resource file from a compiled program, if you want to sync the internal data you might be able to setup a client-server connection using sockets and creating a program that writes the data to the local file from data packets send to your web-app, otherwise retrieving the edited file from where you are hosting might be less complicated (or if you are deploying from the same PC you might be able to get away with a symbolic or hard link)
I've tried this code that is very similar to yours and it's working nicely,
so i think the problem is the way you are picking the path of the file.
public static void main(String[] args){
File file = new File("./localtest.txt");
System.out.println(file.canRead()); //true
System.out.println(file.canWrite()); //true
try {
BufferedWriter out = new BufferedWriter
(new OutputStreamWriter(new FileOutputStream(file),"UTF-8"));
out.append("new line");
out.append("new line 2");
out.append("new line 3");
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
this works
PrintWriter pw= new PrintWriter(
new BufferedWriter(new FileWriter("C:\\foo.txt")));
pw.println("line 1");
pw.close();

How to use the .txt, .xml and .properties file inside the executable jar?

I have a java project which will read a txt file and process that.
For production purpose, I will need to generate an executable jar which contains this txt file.
I use the code like:
BufferedReader br = new BufferedReader(new FileReader("src/txt_src/sample.txt"));
My jar contains txt_src/sample.txt, but can't use it. Instead, if I put a src directory which has src/txt_src/sample.txt structure, the jar works.
It will be better to generate directly by Eclipse.
Thanks in advance!
Treat the file as a resource and give the path as the package hierarchy.
http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream%28java.lang.String%29
You can then take the InputStream and wrap it in an InputStreamReader that is wrapped in a BufferedReader. Wrap it in a BufferedInputStream if you need to define the encoding, which you should do.
new BufferedReader(new InputStreamReader(new BufferedInputStream(this.getResourceAsStream("myPackage/myFile.txt")), "UTF-8"));
Put your files in the assets Folder of your Project and use them with:
InputStream stream = null;
try {
stream = getAssets().open("sample.txt");
}
catch (IOException e) {
e.printStackTrace();
}

Save in another directory JAVA - Very simple question!

I got a folder called DIR and a subfolder called SUB.
the java file i am running is placed in the DIR folder, and now i want to save my small string in a .txt file in the SUB folder.
Could you help me?
PrintWriter out = new PrintWriter(
new OutputStreamWriter(
new FileOutputStream("SUB/myfile.txt")));
out.println("simpleString);
out.close();
This simple task seems very complicated in Java. The reason is, that you can configure everything on the way from the String to the file. You could e.g. specifiy the encoding of the output file, which defaults to platform encoding (e.g. "win1252" for Windows in most parts of the western hemisphere). To write UTF-8 files use:
PrintWriter out = new PrintWriter(
new OutputStreamWriter(
new FileOutputStream("SUB/myfile.txt"),"UTF-8"));
out.println("simpleString);
out.close();
The PrintWriter also has a "flush immediately" option, which is nice for logfiles you want to monitor in the background.
By chaining the IO constructors, you can also increase performance when using a BufferedWriter, because this flushes only to the disk, when a minimum size is reached, or when the stream is closed.
PrintWriter out = new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream("SUB/myfile.txt"),"UTF-8")));
out.println("simpleString);
out.close();
By having to create a FileOutputStream you specify the output should go to the disk, but you can also use any other streamable location, like e.g. an array:
byte[] bytes = new byte[4096];
OutputStream bout = new ByteArrayOutputStream(bout);
PrintWriter out = new PrintWriter(
new OutputStreamWriter(bout,"UTF-8"));
out.println("simpleString);
out.close();
You will love Javas versatility!
Apache org.apache.commons.io.FileUtils class is implemented to reduce amount of boilerplate code..
FileUtils.writeStringToFile(new File("SUB/textFile.txt"),stringData,"UTF-8");

Categories