overwrite file content/bytes - java

I have a (PDF) file that exists on the file system, at a known location. I wish to overwrite the content of that file (with a fresh byte[]).
Best (and most efficient) possible way to do so (using Java APIs)?

public void oneShotAPI(File file, byte[] bytes) throws IOException
{
FileOutputStream fos = null;
try
{
fos = new FileOutputStream(file);
fos.write(bytes);
fos.flush();
} finally
{
if (fos != null)
try
{
fos.close();
} catch (IOException e)
{
// Sad, but true
}
}
}
Call it with:
oneShotAPI(new File("myPDF.png"), byteArray);

There's nothing built into the Java APIs that does this, but if you're looking for a library:
Apache Commons IO has FileUtils.writeByteArrayToFile(File, byte[])
Google Guava has Files.write(byte[], File)
I don't see why any of the short methods posted here wouldn't work, though. There's no actual need for a library IMHO.

Related

Is it good idea to create two different files for reading and writing?

I am building a basic bank application, although the usage of the java language is intermediate level.
There I am using file input and output a lots. Along the way some questions has popped up in my mind about the file-i/o in java.
1) What if I create two different text file for writing and reading objects? Does it make any difference?
2) How about the specifying path (or giving file name), what if I use // instead of \\?
3) Do I necessarily need to create a new file object like this: File file=new File("C://Users//Documents//NetBeansProjects//BankFile_assignment.txt"); in my specific case?
Last but not least if you may wonder about my file-i/o class:
public class ReaderWriter {
public void writeToFile(List<BankAccount> accounts) {
try {
File file = new File("C://Users//Documents//NetBeansProjects//BankFile_assignment.txt");
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(accounts);//take the arrayList
oos.flush();
oos.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public List<BankAccount> readFromFile() {
List<BankAccount> readData = null;
try {
File file = new File("C://Users//Documents//NetBeansProjects//BankFile_assignment.txt");
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
readData = (List<BankAccount>) ois.readObject();
ois.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
return readData;
}
}
1) Better way is to use databases (mySQL, SQLite,...) to access easily to all your datas without I/O worries.
2) If your application might work on different Operating Systems, a safe way to avoid any trouble with the specific symbol of system ( \ on Windows, / on Unix, Mac) is to use File.separator for example. More about this subject .
3) It must work on Windows, but fails on Unix. You can use (with adaptation for path) this instead of: File file = new File(System.getProperty("user.home")+ File.separator + BankFile_assignment.txt); See this .

How to describe content of file rar / zip in jtable from url or path(directory)?

How to describe content of file rar/zip in jtable from url or path directory in java?
I found here and here
But how to open from URL on describe to jtable?
I'd use PrpcessBuilder, shown here, to execute unzip -l or unrar -l and parse the output to create my TableModel. See also How to Use Tables.
You need to model the data some how. Maybe a VirtualFile, this should contain the information you want to display.
You then need to create a model of the that wraps this data in some meaningful way. You'll need a TableModel for this purpose (preferably use the Abstract or Default implementation)
Once you've decided on how you want the model to be laid out, you simply supply the modle to the JTable
For more information check out How to use Tables
UPDATE
You can learn more from the Basic I/O lesson, but here's a (really) basic example of reading the contents of URL to local disk
File outputFile = new File("Somefile on disk.rar");
Inputstream is;
OutputStream os;
try {
is = url.openStream();
os = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int bytesIn = -1;
while ((bytesIn = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesIn);
}
os.flush();
} catch (IOException exp) {
exp.printStackTrace();
} finally {
try {
is.close();
} catch (Exception exp) {
}
try {
os.close();
} catch (Exception exp) {
}
}

Is this the best way to download a file in java?

public void download(String url, String destination) {
BufferedOutputStream localBufferedOutputStream = null;
URLConnection localURLConnection = null;
InputStream localInputStream = null;
try {
URL localURL = new URL(url);
localBufferedOutputStream = new BufferedOutputStream(new FileOutputStream(destination));
localURLConnection = localURL.openConnection();
localInputStream = localURLConnection.getInputStream();
byte[] arrayOfByte = new byte[1024];
int i;
while ((i = localInputStream.read(arrayOfByte)) != -1) {
localBufferedOutputStream.write(arrayOfByte, 0, i);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (localInputStream != null) {
localInputStream.close();
}
if (localBufferedOutputStream != null) {
localBufferedOutputStream.close();
}
} catch (IOException localIOException3) {
System.out.println(localIOException3);
}
}
}
I'm debugging my application and it seems a bit slow. I'm wondering if it's my internet. Is this the proper way to download a file in java? The file is 26mb.
You should always look to libraries such as Apache. They have done all the hard work for you:
http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html
I use
static String readFileToString(File file)
Reads the contents of a file into a String using the default encoding for the VM.
quite a lot.
If you know you have a URL (and so stream) look at:
http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html
You can leave out the BufferedOutputStream since you're already using a buffer yourself. But that's not going to make a big difference.
What may (or may not) make a big difference is using the nio channel classes instead of the streams.
As an alternative and just for reference, you can investigate HTMLUnit. This framework will allow you to download files even on sites where there are browser redirects.
http://htmlunit.sourceforge.net/
It is certainly not the best way. Code that throws away all exceptions is rarely the best way to do any thing. You might also consider not usi g strings as parameters. URI and File would be good alternatives.
If you want to copy streams transferTo is a good way.

Download a non html file with HtmlUnit

I'm writing a JUnit test that involves the downloading of a file from the web app. How do I do that with HtmlUnit?
I don't what kind of file, but maybe code for this test might be helpful. If not try to find answers in other tests.
I'd bet you already solved the problem, but since this question is on google's top results when searching for "htmlunit download", here's the standard solution. downloadLink is the element with the link to the file you intend to download (a button, an input, an anchor...)
try {
InputStream is = downloadLink.click().getWebResponse().getContentAsStream();
try {
File f = new File("filename.extension");
OutputStream os = new FileOutputStream(f);
byte[] bytes = new byte[1024]; // make it bigger if you want. Some recommend 8x, others 100x
while (read = is.read(bytes)) {
os.write(bytes, 0, read);
}
os.close();
is.close();
} catch (IOException ex) {
// Exception handling
}
} catch (IOException ex) {
// Exception handling
}

Problem writing to file

I'm having a problem writing to a file:
FileInputStream fin;
try
{
fin = new FileInputStream ("c:/text.txt");
PrintStream p = new PrintStream(fin);
p.println ("test");
fin.close();
}
catch (IOException ioe)
{
System.err.println (ioe.getMessage);
}
Is there a problem with this code?
You need to use a FileOutputStream.
Get used to the following structure. You'll use it a lot in Java.
PrintStream out = null;
try {
out = new PrintStream(new FileOutputStream("c:/text.txt"));
out.println ("test");
} catch (IOException e) {
System.err.println (e.getMessage);
} finally {
if (out != null) {
try { out.close(): } catch (Exception e) { }
}
out = null; // safe but not strictly necessary unless you reuse fin in the same scope
}
At least until ARM blocks hopefully eventuate in Java 7.
As noted, you should close the PrintStream and not the FileOutputStream so the above is a better form to use.
Problems with that code that immediately strike me:
Non-standard formatting.
Awkward variable names.
The exception handling is not good.
Failure to close the file in the case of exceptions. (Use acquire(); try { use(); } finally { release(); }.
Hidden use of default character encoding.
PrintStream swallows exceptions. BufferedOutputStream is better.
Failure to flush the decorator. It may still have data buffered. Although actually in this case you have left the PrintStream in auto-flush mode, which can be a performance issue.
Use / for a Windows path separator. You might be able to get away with it, but it's not good.
So:
FileOutputStream fileOut = new FileOutputStream(
"c:\\text.txt"
);
try {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
fileOut,
"UTF-8" // Or, say, Charset.defaultCharset()
));
out.write("test");
out.newLine()
out.flush();
} finally {
fileOut.close();
}
The class: FileInputStream is used to read input from a file. If you want to write to the file, you can use: FileOutputStream. If you want to make your life really easy, you can use a BufferedOutputStream as well.
As pointed out, you should close your streams in the finally block. The reason why you want to do that is say your program isn't really small, and it's a larger application. If you forget to close file streams, for example, the application will hold on to it and if you try to do something to it on the file system (read: at least in Windows) you won't be able to it. We've all seen the 'File cannot be deleted because it's still in use' error.
Here's an example of using the FileOutputStream + BufferedOutputStream: http://www.javadb.com/write-to-file-using-bufferedoutputstream.

Categories

Resources