I am not able to read mail content - java

I have a outlook where I have to read subject and body content of the mail in java. Everything works fine, but if I have body with screenshot it throws ERROR: invalid byte sequence for encoding "UTF8": 0x00
I have tried to put the mail as a doc attachment. But no use.
String destFilePath = path + ticketId + "/" + bpFileName;
File f = new File(path + ticketId);
if (!f.exists()) {
f.mkdirs();
}
InputStream input = bp.getInputStream();
byte[] buffer = new byte[4096];
int bytRead = -1;
byte[] byteRead = new byte[4096];
while ((bytRead = input.read(byteRead)) != -1) {
if (byteRead != null) {
String content2 = new String(byteRead, "us-ascii");
if (content2 != null) {
content = content.concat(content2);
}
}
}
input.close();
Expected is text or html content. But it gives xml,html,text, invalid byte sequence exception.

Related

How do I resolve this encoding problem with ZipInputStream?

I'm doing a ZipInputStream request on a UTF-8 encoded zip file.
I get the data through OK, but special German characters are coming out wrong.
Using this page ( http://kellykjones.tripod.com/webtools/ascii_utf8_table.html ) I can see that my code is printing out the two individual chars from the UTF8 encoding column.
i.e. ä is UTF 0xC3,0xA4, and I am getting ä printed out (which are the 0xC3 and 0xA4 chars). Does anyone have any tips?
private InputStream downloadCsv(final String countryCode) {
final String url = baseUrl + countryCode.toUpperCase() + ".zip";
final String fileName = countryCode.toUpperCase() + ".txt";
BufferedInputStream in = null;
ZipInputStream zIn = null;
try {
in = new BufferedInputStream(new URL(url).openStream());
zIn = new ZipInputStream(in, Charset.forName("UTF-8"));
ZipEntry zipEntry;
while ((zipEntry = zIn.getNextEntry()) != null) {
if (zipEntry.getName().equals(fileName)) {
StringBuilder sb = new StringBuilder();
int c;
while((c = zIn.read()) != -1) {
sb.append((char)c);
System.out.println((char)c + " : " + c);
}
return new ByteArrayInputStream(sb.toString().getBytes());
}
}
...
more code
...
For the record, I fixed this using #saka1029s advice, using an InputStreamReader, and would mark it as the accepted answer if I could!
I can't promise my code is the cleanest, but it works now:
BufferedInputStream in = null;
ZipInputStream zIn = null;
InputStreamReader zInReader = null;
try {
in = new BufferedInputStream(new URL(url).openStream());
zIn = new ZipInputStream(in);
ZipEntry zipEntry;
while ((zipEntry = zIn.getNextEntry()) != null) {
if (zipEntry.getName().equals(fileName)) {
StringBuilder sb = new StringBuilder();
zInReader = new InputStreamReader(zIn);
int c;
while((c = zInReader.read()) != -1) {
sb.append((char)c);
}
return new ByteArrayInputStream(sb.toString().getBytes());
}
}

I want to Convert Mysql Blob to String and then String back to Blob

I have stored jar file into a Blob (Mysql table). I could do it with following codes:
blob = rset.getBlob(1);
byte[] bdata = blob.getBytes(1, (int) blob.length());
String s = new String(bdata);
sb.append(s);
Upto here I could do it successfully. But the issue is when I am taking back to Blob then size (length) is increasing to almost double, I dont know why. File is prepared but could not be extracted (unknown format error)
while ((response = reader.readLine()) != null ) {
if(!response.equals("")) {
reader.lines().forEach(line -> sb.append(line));
blob = new javax.sql.rowset.serial.SerialBlob(sb.toString().getBytes());
`enter code here`String filename = "blob.zip";
FileOutputStream fos = new FileOutputStream(filename);
if (blob != null) {
InputStream in = blob.getBinaryStream();
int len = in.available();
int data = 0;
System.out.println("downloading to " + filename);
byte[] bytin = new byte[1024];
while ((data = in.read(bytin)) != -1) {
fos.write(bytin, 0, data);
}
fos.flush();
}

How to get file name while downloading a file in Java?

I have FileDownloader class that downloads the file from google drive and than these files can be used by other classes. I need also to extract filename somehow. The problem is that this solution below works good for direct links, but it doesn't work when links are shorten with bit.ly for example...
Could you please advise how I can change the code to get the right file name?
public class FileDownloader {
private static final int BUFFER_SIZE = 4096;
public static void downloadFile(String fileURL, String saveDir)
throws IOException {
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// checking HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename*=UTF-8''");
if (index > 0) {
fileName = disposition.substring(index + 17,
disposition.length());
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
} else {
System.out.println("No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();
}
Alternate Code to get File details from any HTTP URL using Java API:
URL url = new URL("http://www.example.com/somepath/filename.extension");
System.out.println(FilenameUtils.getBaseName(url.getPath()));
// filename
System.out.println(FilenameUtils.getName(url.getPath()));
// filename.extension

Code that download empty file and supposed not to

I have this part of function where it supposed to download file like pdf from server and store in new directory. It does do this but an empty pdf or text file.How to fix it.
`File urlfile = new File(host + "/" + path);
urlfile.getParentFile().mkdirs();
// create outputstream for request and inputstream for data
// download
FileOutputStream outS = new FileOutputStream(urlfile);
DataInputStream instream = new DataInputStream(newsocket.getInputStream());
// get rid of head part to get to actual file
String l = null;
String lastmodtime = null;
boolean done = false;
while (!(l = DAA.readLine()).equals("")) {
if (!done && l.contains("Last-Modified:")) {
lastmodtime = l.substring(l.indexOf(' ') + 1, l.length());
done = true;
System.out.println(l);
}
}
// read in bytes to correct file name
try {
byte[] inbytes = new byte[16384];
int input;
while ((input = instream.read(inbytes)) != -1) {
outS.write(inbytes, 0, input);
}
}`
You can try this simple code if you want to create a copy of the file or you can even use apache commons io (FileUtils.copyFile(source, dest)) for java copy file operation.
private static void copyFileUsingStream(File source, File dest)
throws IOException {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(source);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
} finally {
is.close();
os.close();
}
}

Reading JPEG Stream over socket gives Null characters

I am reading a .jpg file over InputStream using this code but I am receiving NULNUL...n stream after some text. Ii am reading this file link to file and link of file that I received , link is Written File link.
while ((ret = input.read(imageCharArray)) != -1) {
packet.append(new String(imageCharArray, 0, ret));
totRead += ret;
imageCharArray = new char[4096];
}
file = new File(
Environment.getExternalStorageDirectory()
+ "/FileName_/"
+ m_httpParser.filename + ".jpg");
PrintWriter printWriter = new PrintWriter(file);
// outputStream = new FileOutputStream(file); //also Used FileoutputStream for writting
// outputStream.write(packet.toString().getBytes());//
// ,
printWriter.write(packet.toString());
// outputStream.close();
printWriter.close();
}
I have also tried FileoutputStream but hardlucj for this too as commented in my code.
Edit
I have used this also. I have a content length field upto which i am reading and writing
byte[] bytes = new byte[1024];
int totalReadLength = 0;
// read untill we have bytes
while ((read = inputStream.read(bytes)) != -1
&& contentLength >= (totalReadLength)) {
outputStream.write(bytes, 0, read);
totalReadLength += read;
System.out.println(" read size ======= "
+ read + " totalReadLength = "
+ totalReadLength);
}
String is not a container for binary data, and PrintWriter isn't a way to write it. Get rid of all, all, the conversions between bytes and String and vice versa, and just transfer the bytes with input and output streams:
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
If you need to constrain the number of bytes read from the input, you have to do that before calling read(), and you also have to constrain the read() correctly:
while (total < length && (count = in.read(buffer, 0, length-total > buffer.length ? buffer.length: (int)(length-total))) > 0)
{
total += count;
out.write(buffer, 0, count);
}
I tested it in my Nexus4 and it's working for me. Here is the snippet of code what I tried :
public void saveImage(String urlPath)throws Exception{
String fileName = "kumar.jpg";
File folder = new File("/sdcard/MyImages/");
// have the object build the directory structure, if needed.
folder.mkdirs();
final File output = new File(folder,
fileName);
if (output.exists()) {
output.delete();
}
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlPath);
stream = url.openConnection().getInputStream();
// InputStreamReader reader = new InputStreamReader(stream);
DataInputStream dis = new DataInputStream(url.openConnection().getInputStream());
byte[] fileData = new byte[url.openConnection().getContentLength()];
for (int x = 0; x < fileData.length; x++) { // fill byte array with bytes from the data input stream
fileData[x] = dis.readByte();
}
dis.close();
fos = new FileOutputStream(output.getPath());
fos.write(fileData);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Just Call the above function in a background thread and pass your url. It'll work for sure. Let me know if it helps.
You can check below code.
destinationFile = new File(
Environment.getExternalStorageDirectory()
+ "/FileName_/"
+ m_httpParser.filename + ".jpg");
BufferedOutputStream buffer = new BufferedOutputStream(new FileOutputStream(destinationFile));
byte byt[] = new byte[1024];
int i;
for (long l = 0L; (i = input.read(byt)) != -1; l += i ) {
buffer.write(byt, 0, i);
}
buffer.close();

Categories

Resources