org.apache.commons.fileupload.disk.DiskFileItem is not created properly? - java

I am trying to use the code shown in the following example:
java.lang.NullPointerException while creating DiskFileItem
My Test method contains the following code:
final File TEST_FILE = new File("C:/my_text.txt");
final DiskFileItem diskFileItem = new DiskFileItem("fileData", "text/plain", true, TEST_FILE.getName(), 100000000, TEST_FILE.getParentFile());
diskFileItem.getOutputStream();
System.out.println("diskFileItem.getString() = " + diskFileItem.getString());
The text file exists in this location but the last line in the above code does not output the file content.
Any idea why?
N.B.
The following does print the file content:
BufferedReader input = new BufferedReader(new FileReader(TEST_FILE));
String line = null;
while (( line = input.readLine()) != null){
System.out.println(line);
}

In your first code snip you use an OutputStream and it doesn't work. In the second part you use an InputStream (or whatever impl of this) and it works :) You might want to try with getInputStream() instead... OutputStream is to write bytes not reading.
http://commons.apache.org/fileupload/apidocs/org/apache/commons/fileupload/disk/DiskFileItem.html
try this one, it's simple and from scratch just to help :
final File TEST_FILE = new File("D:/my_text.txt");
//final DiskFileItem diskFileItem = new DiskFileItem("fileData", "text/plain", true, TEST_FILE.getName(), 100000000, TEST_FILE);
try
{
DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("fileData", "text/plain", true, TEST_FILE.getName());
InputStream input = new FileInputStream(TEST_FILE);
OutputStream os = fileItem.getOutputStream();
int ret = input.read();
while ( ret != -1 )
{
os.write(ret);
ret = input.read();
}
os.flush();
System.out.println("diskFileItem.getString() = " + fileItem.getString());
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

A condensed solution with apache IOUtils :
final File TEST_FILE = new File("C:/my_text.txt");
final DiskFileItem diskFileItem = new DiskFileItem("fileData", "text/plain", true, TEST_FILE.getName(), 100000000, TEST_FILE.getParentFile());
InputStream input = new FileInputStream(TEST_FILE);
OutputStream os = diskFileItem.getOutputStream();
IOUtils.copy(input, os);
System.out.println("diskFileItem.getString() = " + diskFileItem.getString());

Related

Creating a download for zip file containing text/csv from string variables

I currently need to create a zip file for downloading. This should contain two (2) csv files that are to be created from string variables. I'm at a loss on how I should do this. My draft is below.
public #ResponseBody Object getFileV1(HttpServletRequest request, HttpServletResponse response) {
try {
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=Reassigned Tickets Report " + new Date().toString() + ".zip");
String stringValue1 = "This is a test value for csv1";
String stringValue2 = "This is a test value for csv2";
InputStream is1 = new ByteArrayInputStream(stringValue1.getBytes("UTF-8"));
InputStream is2 = new ByteArrayInputStream(stringValue2.getBytes("UTF-8"));
ZipInputStream zin;
ZipEntry entry;
ZipOutputStream zout= new ZipOutputStream(response.getOutputStream());
zin = new ZipInputStream(is1);
entry = zin.getNextEntry();
zout.putNextEntry(entry);
zin = new ZipInputStream(is2);
entry = zin.getNextEntry();
zout.putNextEntry(entry);
zout.closeEntry();
zin.close();
zout.close();
response.flushBuffer();
return null;
} catch (Exception e) {
e.printStackTrace();
return e;
}
}
Obviously this is not working. Probably because I'm still a novice at this. Please bear with me.
I get a "java.lang.NullPointerException" at the line where "zout.putNextEntry" is called. Would appreciate your advice. Thank you in advance.
I solved my problem after a day of looking around. This works for me. But I'm not sure if this is the most efficient way.
public #ResponseBody Object getFileV1(HttpServletRequest request, HttpServletResponse response) {
try {
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=Test Report " + new Date().toString() + ".zip");
String stringValue1 = "This is a test value for csv1";
String stringValue2 = "This is a test value for csv2";
PrintWriter writer1 = new PrintWriter(new OutputStreamWriter(new FileOutputStream("stringValue1.csv"), "UTF-8"));
writer1.print(stringValue1);
writer1.close();
PrintWriter writer2 = new PrintWriter(new OutputStreamWriter(new FileOutputStream("stringValue2.csv"), "UTF-8"));
writer2.print(stringValue2);
writer2.close();
File file1 = new File("stringValue1.csv");
File file2 = new File("stringValue2.csv");
filesToZip(response, file1, file2);
file1.delete();
file2.delete();
response.flushBuffer();
return null;
} catch (Exception e) {
e.printStackTrace();
return e;
}
}
This is the method I got from another thread with a few edits.
public static void filesToZip(HttpServletResponse response, File... files) throws IOException {
// Create a buffer for reading the files
byte[] buf = new byte[1024];
// create the ZIP file
ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
// compress the files
for(int i=0; i<files.length; i++) {
FileInputStream in = new FileInputStream(files[i].getName());
// add ZIP entry to output stream
out.putNextEntry(new ZipEntry(files[i].getName()));
// transfer bytes from the file to the ZIP file
int len;
while((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// complete the entry
out.closeEntry();
in.close();
}
// complete the ZIP file
out.close();
}
The only thing I don't love is that I had to create temporary files and delete them after processing.

Not in GZIP Format - JAVA

I'm trying to write compressed data to a file and then read in the data and decompress it using the GZIP library. I've tried changing all formatting to StandardCharsets.UTF-8 and ISO-8859-1 and neither have fixed the GZIP format error. I'm wondering if it could possible have to do with the file I'm reading in? Here's the compression function:
public static byte[] compress(String originalFile, String compressFile) throws IOException {
// read in data from text file
// The name of the file to open.
String fileName = originalFile;
// This will reference one line at a time
String line = null;
String original = "";
try {
// FileReader reads text files in the default encoding.
FileReader fileReader =
new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
original.concat(line);
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
// create a new output stream for original string
try (ByteArrayOutputStream out = new ByteArrayOutputStream())
{
try (GZIPOutputStream gzip = new GZIPOutputStream(out))
{
gzip.write(original.getBytes(StandardCharsets.UTF_8));
}
byte[] compressed = out.toByteArray();
out.close();
String compressedFileName = compressFile;
try {
// Assume default encoding.
FileWriter fileWriter =
new FileWriter(compressedFileName);
// Always wrap FileWriter in BufferedWriter.
BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);
// Note that write() does not automatically
// append a newline character.
String compressedStr = compressed.toString();
bufferedWriter.write(compressedStr);
// Always close files.
bufferedWriter.close();
}
catch(IOException ex) {
System.out.println(
"Error writing to file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
return compressed;
}
}
(I'm receiving the error on the line in the following decompression function) -
GZIPInputStream compressedByteArrayStream = new GZIPInputStream(new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)));
Decompression Function:
public static String decompress(String file) throws IOException {
byte[] compressed = {};
String s = "";
File fileName = new File(file);
FileInputStream fin = null;
try {
// create FileInputStream object
fin = new FileInputStream(fileName);
// Reads up to certain bytes of data from this input stream into an array of bytes.
fin.read(compressed);
//create string from byte array
s = new String(compressed);
System.out.println("File content: " + s);
}
catch (FileNotFoundException e) {
System.out.println("File not found" + e);
}
catch (IOException ioe) {
System.out.println("Exception while reading file " + ioe);
}
finally {
// close the streams using close method
try {
if (fin != null) {
fin.close();
}
}
catch (IOException ioe) {
System.out.println("Error while closing stream: " + ioe);
}
}
// create a new input string for compressed byte array
GZIPInputStream compressedByteArrayStream = new GZIPInputStream(new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)));
ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
byte[] buffer = new byte[8192];
// create a string builder and byte reader for the compressed byte array
BufferedReader decompressionBr = new BufferedReader(new InputStreamReader(compressedByteArrayStream, StandardCharsets.UTF_8));
StringBuilder decompressionSb = new StringBuilder();
// write data to decompressed string
String line1;
while((line1 = decompressionBr.readLine()) != null) {
decompressionSb.append(line1);
}
decompressionBr.close();
int len;
String uncompressedStr = "";
while((len = compressedByteArrayStream.read(buffer)) > 0) {
uncompressedStr = byteOutput.toString();
}
compressedByteArrayStream.close();
return uncompressedStr;
}
Here's the error message that i am receiving:
[B#7852e922
File content:
java.io.EOFException
at java.util.zip.GZIPInputStream.readUByte(GZIPInputStream.java:268)
at java.util.zip.GZIPInputStream.readUShort(GZIPInputStream.java:258)
at java.util.zip.GZIPInputStream.readHeader(GZIPInputStream.java:164)
at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:79)
at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:91)
at org.kingswoodoxford.Compression.decompress(Compression.java:136)
at org.kingswoodoxford.Compression.main(Compression.java:183)
Any suggestions as to how I might be able to fix this?
When you read the file you discard the new line at the end of each line.
A more efficient option which does do this is to copy a block i.e. char[] at a time. You can also convert the text as you go rather than creating a String or a byte[].
BTW original.concat(line); returns the concatenated string which you are discarding.
The real problem is you write to one stream and close a different one. This means that if there is any buffered data at the end of the file (and this is highly likely) the end of the file will be truncated and when you read it it will complain that your file is incomplete or EOFException.
Here is a shorter example
public static void compress(String originalFile, String compressFile) throws IOException {
char[] buffer = new char[8192];
try (
FileReader reader = new FileReader(originalFile);
Writer writer = new OutputStreamWriter(
new GZIPOutputStream(new FileOutputStream(compressFile)));
) {
for (int len; (len = reader.read(buffer)) > 0; )
writer.write(buffer, 0, len);
}
}
In the decompress, don't encode binary as text and attempt to get back the same data. It will almost certainly be corrupted. Try to use a buffer and a loop like I did for compress. i.e. it shouldn't be any more complicated.

How to convert MultipartFile into byte stream

//Or any other solution to saving multipartfile into DB.
I tried with this way but getting error.
File fileOne = new File("file.getOrignalFileName");//what should be kept inside this method
byte[] bFile = new byte[(int) fileOne.length()];
try {
FileInputStream fileInputStream = new FileInputStream(fileOne);
//convert file into array of bytes
fileInputStream.read(bFile);
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
questionDao.saveImage(bFile);
MultipartFile file;
byte [] byteArr=file.getBytes();
InputStream inputStream = new ByteArrayInputStream(byteArr);
//Start Photo Upload with Adhaar No//
if (simpleLoanDto.getPic() != null && simpleLoanDto.getAdharNo() != null) {
String ServerDirPath = globalVeriables.getAPath() + "\\";
File ServerDir = new File(ServerDirPath);
if (!ServerDir.exists()) {
ServerDir.mkdirs();
}
// Giving File operation permission for LINUX//
IOperation.setFileFolderPermission(ServerDirPath);
MultipartFile originalPic = simpleLoanDto.getPic();
byte[] ImageInByte = originalPic.getBytes();
FileOutputStream fosFor = new FileOutputStream(
new File(ServerDirPath + "\\" + simpleLoanDto.getAdharNo() + "_"+simpleLoanDto.getApplicantName()+"_.jpg"));
fosFor.write(ImageInByte);
fosFor.close();
}
//End Photo Upload with Adhaar No//

Java. How to append text to top of file.txt [duplicate]

This question already has answers here:
Writing in the beginning of a text file Java
(6 answers)
Closed 9 years ago.
I need to add text to beggining of text file via Java.
For example I have test.txt file with data:
Peter
John
Alice
I need to add(to top of file):
Jennifer
It should be:
Jennifer
Peter
John
Alice
I have part of code, but It append data to end of file, I need to make It that added text to top of file:
public static void irasymas(String irasymai){
try {
File file = new File("src/lt/test.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(irasymai+ "\r\n");
bw.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
I have tried this, but this only deletes all data from file and not insert any text:
public static void main(String[] args) throws IOException {
BufferedReader reader = null;
BufferedWriter writer = null;
ArrayList list = new ArrayList();
try {
reader = new BufferedReader(new FileReader("src/lt/test.txt"));
String tmp;
while ((tmp = reader.readLine()) != null)
list.add(tmp);
OUtil.closeReader(reader);
list.add(0, "Start Text");
list.add("End Text");
writer = new BufferedWriter(new FileWriter("src/lt/test.txt"));
for (int i = 0; i < list.size(); i++)
writer.write(list.get(i) + "\r\n");
} catch (Exception e) {
e.printStackTrace();
} finally {
OUtil.closeReader(reader);
OUtil.closeWriter(writer);
}
}
Thank you for help.
File mFile = new File("src/lt/test.txt");
FileInputStream fis = new FileInputStream(mFile);
BufferedReader br = new BufferedReader(fis);
String result = "";
String line = "";
while( (line = br.readLine()) != null){
result = result + line;
}
result = "Jennifer" + result;
mFile.delete();
FileOutputStream fos = new FileOutputStream(mFile);
fos.write(result.getBytes());
fos.flush();
The idea is read it all, add the string in the front. Delete old file. Create the new file with eited String.
You can use RandomAccessFile to and seek the cursor to 0th position using seek(long position) method, before starting to write.
As explained in this thread
RandomAccessFile f = new RandomAccessFile(new File("yourFile.txt"), "rw");
f.seek(0); // to the beginning
f.write("Jennifer".getBytes());
f.close();
Edit: As pointed out below by many comments, this solution overwrites the file content from beginning. To completely replace the content, the File may have to be deleted and re-written.
The below code worked for me. Again it will obviously replace the bytes at the beginning of the file. If you can certain how many bytes of replacement will be done in advance then you can use this. Otherwise, follow the earlier answers or take a look at here Writing in the beginning of a text file Java
String str = "Jennifer";
byte data[] = str.getBytes();
try {
RandomAccessFile f = new RandomAccessFile(new File("src/lt/test.txt"), "rw");
f.getChannel().position(0);
f.write(data);
f.close();
} catch (IOException e) {
e.printStackTrace();
}

How to write String to txt file and send it to server

I want to develop an application in android in which I need to capture image and convert that image to string and write that string in txt file and send it to server where server reads that file and convert that string to image again...
now i have done with image taking part and converting that image into string and writing that string to txt file.
but when am try to read that file and convert that string into the image it's not working...
Code for converting image into string is
File imageFile = new File(path);
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte[] image = stream.toByteArray();
imgstr = Base64.encodeToString(image, 0);
Code for writing that into file is
File file = new File("new.txt");
FileWriter w = new FileWriter("/sdcard/new/new.txt");
BufferedWriter out = new BufferedWriter(w);
out.write(data);
out.flush();
out.close();
And code for read that file and convert that string to image again is
FileInputStream fstream = new FileInputStream("/sdcard/new/new.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
ArrayList list=new ArrayList();
while ((strLine = br.readLine()) != null)
{
list.add(strLine);
}
Iterator itr;
for (itr=list.iterator(); itr.hasNext(); )
{
String str=itr.next().toString();
StringBuffer sb=new StringBuffer(str);
int length=sb.length();
String imageDataString = sb.substring(0, length);
byte[] decodedString = Base64.decode(imageDataString, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0,decodedString.length);
FileOutputStream imageOutFile = new FileOutputStream("/sdcard/new/android.jpg");
imageOutFile.write(decodedString);
imageOutFile.close();
System.out.println("File converted");
but its not converting that string into image
please tell me solution for it...
if all you need is uploading files via ftp from android to web server, this will do the trick (working from froyo up - BUT you must import apache commons and install a copy inside your "src" folder):
import java.io.FileInputStream;
import org.apache.commons.net.ftp.FTPClient;
import android.util.Log;
public class FtpFileUp implements Runnable {
private final String TAG = "FTPfile";
boolean flagFTPOK = false;
String fileName, fileDirSubLocalName, fileDirSubRemoteName;
String fileDirName = NavigationActivity.fileDirName;
FtpFileUp (String fileNameIn, String fileDirSubLocalNameIn, String fileDirSubRemoteNameIn) {
fileName = (String) fileNameIn;
fileDirSubLocalName = (String) fileDirSubLocalNameIn;
fileDirSubRemoteName = (String) fileDirSubRemoteNameIn;
}
FtpFileUp (String fileNameIn) {
String fileDirSubNameIn = "";
fileName = (String) fileNameIn;
fileDirSubLocalName = (String) fileDirSubNameIn;
fileDirSubRemoteName = (String) fileDirSubNameIn;
}
FtpFileUp (String fileNameIn, String fileDirSubNameIn) {
fileName = (String) fileNameIn;
fileDirSubLocalName = (String) fileDirSubNameIn;
fileDirSubRemoteName = (String) fileDirSubNameIn;
}
#Override
public void run() {
String ftpConnectString = "ftp.yourdomain.com";
if (fileDirSubRemoteName != "") fileDirSubRemoteName += "/";
if (fileDirSubLocalName != "") fileDirSubLocalName += "/";
FTPClient ftpCli = new FTPClient();
try {
FileInputStream fis = new FileInputStream(fileDirName+"/"+fileDirSubLocalName+fileName);
ftpCli.connect(ftpConnectString);
ftpCli.login("user", "password");
Log.i(TAG, "ok ftp "+ftpCli.getDataConnectionMode());
ftpCli.storeFile("/"+fileDirSubRemoteName+fileName, fis);
fis.close();
flagFTPOK = true;
} catch (Exception except) {
Log.i(TAG, "ftp up FAIL "+except);
}
}
}
which you would call using the following code (encapsulated by TRY CATCH)
Thread ftpThread01 = new Thread(new FtpFileUp("fileName", "", "/www/android/imgUpload"));
ftpThread01.start();
NOTE: as you can see, there are 2 alternative constructors that you may use to automatize your ftp, by storing default locations. they may be removed with no harm.

Categories