Writing a File object to a file in java - java

For a class, I have to send a file of any type from my client to a server. I have to handle each packet individually and use UDP. I have managed to transfer the file from the client to the server, and I now have a file object which I cannot figure out how to save to a user specified directory.
f = new File(path + '\\' + filename);//path and filename are user specified.
FileOutputStream foutput = new FileOutputStream(f);
ObjectOutputStream output = new ObjectOutputStream(foutput);
output.writeObject(result);//result is a File
output.flush();
output.close();
Any time I run this code, it writes a new file with the appropriate name, but the text file I am testing ends up just containing gibberish. Is there any way to convert the File object to a file in the appropriate directory?
EDIT: As it turns out, I was misunderstanding what, exactly, a file is. I have not been transferring the data, but rather the path. How do I transfer an actual file?

ObjectOutputStream is a class that outputs a specific format of data to a text file. Only ObjectInputStream's readObject() can decoding that text file.
If you open the text file , it is just gibberish ,as you have seen.
you want this:
FileOutputStream fos = new FileOutputStream(path + '\\' + filename);
FileInputStream fis = new FileInputStream(result);
byte[] buf = new byte[1024];
int hasRead = 0;
while((hasRead = fis.read(buf)) > 0){
fos.write(buf, 0, hasRead);
}
fis.close();
fos.close();

If I understand your question, how about using a FileWriter?
File result = new File("result.txt");
result.createNewFile();
FileWriter writer = new FileWriter(result);
writer.write("Hello user3821496\n"); //just an example how you can write a String to it
writer.flush();
writer.close();

Related

java - HttpServlet file download

I tried to create a file, write to it and then turn the file into an input stream and transfer its bytes to the output stream of the HTTP response. But I get the message "/tmp/mozilla_xxxx/33JJ1OHw.md.part could not be saved, because the source file could not be read." when testing it.
Here's the code that does this part.
f = new File("f.md");
f.createNewFile();
fw = new FileWriter(f);
fw.append("#" + query + "\n" + queryResult);
fw.close();
resp.setContentType("text/markdown");
OutputStream out = resp.getOutputStream();
FileInputStream in = new FileInputStream(f);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.flush();
As you can see in the documentation, File class is not meant to read the actual file content, it is just...
An abstract representation of file and directory pathnames.
But, there are many ways of getting file's content, just use one of the following classes: FileReader, BufferedReader, Scanner and Files.
Here you'll see different examples to do that, just use the one you find better. Different ways of Reading a text file in Java

Amazon Merchant Fulfilment Create Shipment Label

I am trying to get the shipment label from amazon merchant fulfillment as per the instructions mentioned on the Amazon pages.
"To obtain the actual PDF document, you must decode the Base64-encoded string, save it as a binary file with a “.zip” extension, and then extract the PDF file from the ZIP file."
Has any one got it to work. I have tried couple of things but every time i get blank pdf.
Here is my code. Can please some body guide me if I am doing it correctly
byte[] decodedBytes = Base64.decodeBase64(contents);
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream("c:\\output\\asdwd.zip")));
//now create the entry in zip file
ZipEntry entry = new ZipEntry("asd.pdf");
zos.putNextEntry(entry);
zos.write(decodedBytes);
zos.close();
The instructions say to save the bytes as a binary file with the extension .zip.
What you are actually doing is creating a ZIP file with the contents of the byte array as an entry.
According to my reading of the instructions, your code should do this:
byte[] decodedBytes = Base64.decodeBase64(contents);
FileOutputStream fos = new FileOutputStream("c:\\output\\asdwd.zip");
fos.write(decodedBytes);
fos.close();
Or better still:
byte[] decodedBytes = Base64.decodeBase64(contents);
try (FileOutputStream fos = new FileOutputStream("c:\\output\\asdwd.zip")) {
fos.write(decodedBytes);
}
Then using a ZIP tool or a web browser, open asdwd.zip, find the entry containing the PDF, and extract it or print it.
Here is the code to generate a shipping label in case somebody needs it.
byte[] decoded = Base64.decodeBase64(contents);
try (FileOutputStream fos = new FileOutputStream(zipFilePath + amazonOrderId + zipFileName)) {
fos.write(decoded);
fos.close();
}
file = new File(destDirectory + amazonOrderId + pngFile);
if (file.exists()) {
file.delete();
}
try (OutputStream out = new FileOutputStream(destDirectory + amazonOrderId + pngFile)) {
try (InputStream in = new GZIPInputStream(
new FileInputStream(zipFilePath + amazonOrderId + zipFileName))) {
byte[] buffer = new byte[65536];
int noRead;
while ((noRead = in.read(buffer)) != -1) {
out.write(buffer, 0, noRead);
}
}
}

How to copy files in JAVA by bufferedInputStream and bufferedOutputStream?

I would like to use bufferedInputStream and bufferedOutputStream to copy large binary files from source file to destination file.
Here is my code:
byte[] buffer = new byte[1000];
try {
FileInputStream fis = new FileInputStream(args[0]);
BufferedInputStream bis = new BufferedInputStream(fis);
FileOutputStream fos = new FileOutputStream(args[1]);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int numBytes;
while ((numBytes = bis.read(buffer))!= -1)
{
bos.write(buffer);
}
//bos.flush();
//bos.write("\u001a");
System.out.println(args[0]+ " is successfully copied to "+args[1]);
bis.close();
bos.close();
} catch (IOException e)
{
e.printStackTrace();
}
I can successfully copy but then I use
cmp src dest
in the command line to compare two files.
The error message
cmp: EOF on files
appears. May I know where I was wrong?
This is the mistake:
bos.write(buffer);
You're writing out the whole buffer, even if you only read data into part of it. You should use:
bos.write(buffer, 0, numBytes);
I'd also suggest using try-with-resources if you're using Java 7 or later, or put the close calls in a finally block otherwise.
As Steffen notes, Files.copy is a simpler approach if that's available to you.
If you are using Java 8 try the Files.copy(Path source, Path target) method.
you need to close your FileOutputStream and FileInputStream
Also you can use FileChannel to copy like as follows
FileChannel from = new FileInputStream(sourceFile).getChannel();
FileChanngel to = new FileOutputStream(destFile).getChannel();
to.transferFrom(from, 0, from.size());
from.close();
to.close();
You could use IOUtils from apatch-commons library
I think copyLarge fucntion it that you need

Java servlet and IO: Create a file without saving to disk and sending it to the user

I`m hoping can help me out with a file creation/response question.
I know how to create and save a file. I know how to send that file back to the user via a ServletOutputStream.
But what I need is to create a file, without saving it on the disk, and then send that file via the ServletOutputStream.
The code above explains the parts that I have. Any help appreciated. Thanks in Advance.
// This Creates a file
//
String text = "These days run away like horses over the hill";
File file = new File("MyFile.txt");
Writer writer = new BufferedWriter(new FileWriter(file));
writer.write(text);
writer.close();
// Missing link goes here
//
// This sends file to browser
//
InputStream inputStream = null;
inputStream = new FileInputStream("C:\\MyFile.txt");
byte[] buffer = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytesRead;
while ( (bytesRead = inputStream.read(buffer)) != -1)
baos.write(buffer, 0, bytesRead);
response.setContentType("text/html");
response.addHeader("Content-Disposition", "attachment; filename=Invoice.txt");
byte[] outBuf = baos.toByteArray();
stream = response.getOutputStream();
stream.write(outBuf);
You don't need to save off a file, just use a ByteArray stream, try something like this:
inputStream = new ByteArrayInputStream(text.getBytes());
Or, even simpler, just do:
stream.write(text.getBytes());
As cHao suggests, use text.getBytes("UTF-8") or something similar to specify a charset other than the system default. The list of available charsets is available in the API docs for Charset.

URL Connection (FTP) in Java - Simple Question

I have a simple question. I'm trying to upload a file to my ftp server in Java.
I have a file on my computer, and I want to make a copy of that file and upload it. I tried manually writing each byte of the file to the output stream, but that doesn't work for complicated files, like zip files or pdf files.
File file = some file on my computer;
String name = file.getName();
URL url = new URL("ftp://user:password#domain.com/" + name +";type=i");
URLConnection urlc = url.openConnection();
OutputStream os = urlc.getOutputStream();
//then what do I do?
Just for kicks, here is what I tried to do:
OutputStream os = urlc.getOutputStream();
BufferedReader br = new BufferedReader(new FileReader(file));
String line = br.readLine();
while(line != null && (!line.equals(""))) {
os.write(line.getBytes());
os.write("\n".getBytes());
line = br.readLine();
}
os.close();
For example, when I do this with a pdf and then try and open the pdf that I run with this program, it says an error occurred when trying to open the pdf. I'm guessing because I am writing a "\n" to the file? How do I copy the file without doing this?
Do not use any of the Reader or Writer classes when you're trying to copy the byte-for-byte exact contents of a binary file. Use these only for plain text! Instead, use the InputStream and OutputStream classes; they do not interpret the data at all, while the Reader and Writer classes interpret the data as characters. For example
OutputStream os = urlc.getOutputStream();
FileInputStreamReader fis = new FileInputStream(file);
byte[] buffer = new byte[1000];
int count = 0;
while((count = fis.read(buffer)) > 0) {
os.write(buffer, 0, count);
}
Whether your URLConnection usage is correct here, I don't know; using Apache Commons FTP (as suggested elsewhere) would be an excellent idea. Regardless, this would be the way to read the file.
Use a BufferedInputStream to read and BufferedOutputStream to write. Take a look at this post: http://www.ajaxapp.com/2009/02/21/a-simple-java-ftp-connection-file-download-and-upload/
InputStream is = new FileInputStream(localfilename);
BufferedInputStream bis = new BufferedInputStream(is);
OutputStream os =m_client.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(os);
byte[] buffer = new byte[1024];
int readCount;
while( (readCount = bis.read(buffer)) > 0) {
bos.write(buffer, 0, readCount);
}
bos.close();
FTP usually opens another connection for data transfer.
So I am not convinced that this approach with URLConnection is going
to work.
I highly recommend that you use specialized ftp client. Apache commons
may have one.
Check this out
http://commons.apache.org/net/api/org/apache/commons/net/ftp/FTPClient.html

Categories

Resources