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

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.

Related

Zip file containing more than one file is sent as string. How to read the string and extract individual files in Java?

Our external application sends the zip file name and content as two strings in the response to an API call. I converted the string to bytearray and used zipinputstream to read the bytearray. If the zip file contains only one file, I am able to read the string and extract the zipped file contents into a separate string. Below is the code snippet I used to extract the file content.
If the zipped file contains more than one file and the entire zipped content is sent as a single string, how do I extract individual file contents into separate strings? How to identify the end of each file in the string?
byte[] data = Base64Util.decodeToByteArray(ZipString);
ByteArrayInputStream bais = new ByteArrayInputStream(data);
ZipInputStream zin = new ZipInputStream(new BufferedInputStream(bais));
ZipEntry ze = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] b = new byte[4096];
String ZippedFileName = new String();
String ZippedFileData = new String();
try
{
while((ze = zin.getNextEntry()) != null)
{
ZippedFileName = ze.getName();
while((zin.read(b,0,4096))!= -1)
{
baos.write(b,0,4096);
}
}
byte[] out = baos.toByteArray();
ZippedFileData = Base64Util.encodeToString(out);
zin.close();
bais.close();
baos.close();
}
catch(Exception Ex)
{
Ex.toString();
}
Actually I think I was presenting the base64 file in string form incorrectly. For one thing, if line feeds are present in the input, it doesn't like it. If you're working on a Unix based system, you can run the below with something like java Unzip64
"$(cat a.zip | base64 | tr -d '\n')"
The following is working fine for me
import java.util.zip.ZipInputStream;
import java.util.zip.ZipEntry;
import java.util.Base64;
import java.util.Map;
import java.util.HashMap;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
public class Unzip64 {
public static void main(String[] args) {
System.out.println(Unzip64.getEntriesAndContents(args[0]));
}
public static Map<String, String> getEntriesAndContents(String base64Zip) {
Map<String, String> result = new HashMap<>();
try {
byte[] data = Base64.getDecoder().decode(base64Zip);
ByteArrayInputStream bais = new ByteArrayInputStream(data);
try (ZipInputStream zin = new ZipInputStream(bais)) {
ZipEntry ze = null;
byte[] b = new byte[4096];
while ((ze = zin.getNextEntry()) != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int numRead = -1;
String entryName = ze.getName();
while ((numRead = zin.read(b, 0, b.length)) > -1) {
baos.write(b, 0, numRead);
}
String entryData = new String(baos.toByteArray());
result.put(entryName, entryData);
baos = null;
zin.closeEntry();
}
}
} catch (Throwable t) {
t.printStackTrace();
}
return result;
}
}
And here's a sample to run:
UEsDBAoAAAgAAKdCJ1UAAAAAAAAAAAAAAAAHAAQAcm9vdC9hL/7KAABQSwMEFAAICAgAp0InVQAAAAAAAAAAAAAAAAwAAAByb290L2EvYS50eHRL5AIAUEsHCAeh6t0EAAAAAgAAAFBLAwQUAAgICACnQidVAAAAAAAAAAAAAAAADAAAAHJvb3QvYS9iLnR4dEviAgBQSwcIxPLH9gQAAAACAAAAUEsDBBQACAgIAKdCJ1UAAAAAAAAAAAAAAAAMAAAAcm9vdC9hL2MudHh0S+YCAFBLBwiFw9zvBAAAAAIAAABQSwECCgAKAAAIAACnQidVAAAAAAAAAAAAAAAABwAEAAAAAAAAAAAAAAAAAAAAcm9vdC9hL/7KAABQSwECFAAUAAgICACnQidVB6Hq3QQAAAACAAAADAAAAAAAAAAAAAAAAAApAAAAcm9vdC9hL2EudHh0UEsBAhQAFAAICAgAp0InVcTyx/YEAAAAAgAAAAwAAAAAAAAAAAAAAAAAZwAAAHJvb3QvYS9iLnR4dFBLAQIUABQACAgIAKdCJ1WFw9zvBAAAAAIAAAAMAAAAAAAAAAAAAAAAAKUAAAByb290L2EvYy50eHRQSwUGAAAAAAQABADnAAAA4wAAAAAA

How to pass file byte array from Java to .Net API and restore byte array to file

I need to pass the file from Java program to .NET api as Byte Array and restore that file through that .Net API.
I have tried to convert to string and pass and as mentioned below but not working.
Java client code:
private String getBytesFromFiles(String path){
try{
logger.info("Accessing the document====> "+path);
File file = new File(path);
InputStream inputStream = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()];
inputStream.read(bytes);
logger.info("Byte array converted to String");
String res = new String(bytes);
return res;
}catch(Exception e){
logger.info("Error at reading the document====> "+e);
//throw new RuntimeException(e);
}
return null;
}
.Net api code:
public string UploadToDBMultiClaims(string strDept, string strPolicyNo1, string strPolicyNo2, List<string> lstClaimNo, string strDocumentName,
string strFileDate, string strRemark, string strCurrentUser, String btBinaryBuffer){
byte[] bytes = new byte[btBinaryBuffer.Length * sizeof(char)];
System.Buffer.BlockCopy(btBinaryBuffer.ToCharArray(), 0, bytes, 0, bytes.Length);
string strDocID = "xyz"
string path = ConfigurationManager.AppSettings["FilePath"].ToString() + DateTime.Today.ToString("yyyyMMdd") + #"\";
string fileName = path + strDocID + ".pdf";
System.IO.File.WriteAllBytes(fileName, bytes);
return "1";
}

unable to write Base64 image data on FTP server

I have encountered the problem to write Base64image data on FTP.
When I write it on local drive, The photo is appeared clearly.
But, When I write it on FTP server, it's appeared like spoiled images.
when I write it on local drive, it's shown like this enter image description here
I have attached the picture on FTP . enter image description here
Here is my code.
private static String testFilesDir = "C:\\Storage";
public String getIncidentPhotoByID(int incident_id, int photoId) {
String base64Image = null;
WebSSLClient client = new WebSSLClient();
Response response =client.createRequest(PropertiesUtil.getOracleCloudRestUrL() + "/mobile/platform/storage/collections/incident_photos_collection/objects/incident_462_03").get();
String jsonResponse = response.readEntity(String.class);
base64Image = jsonResponse;
FTPClient ftp = new FTPClient();
FileInputStream fis = null;
String filename = "incident_462_03";
String[] strings = base64Image.split(",");
String extension;
switch (strings[0]) {//check image's extension
case "data:image/jpeg;base64":
extension = "jpeg";
break;
case "data:image/png;base64":
extension = "png";
break;
default://should write cases for more images types
extension = "jpg";
break;
}
//convert base64 string to binary data
byte[] data1 = Base64.decodeBase64(strings[1]);
/*
String path = testFilesDir+"/"+filename+"."+ extension;
File file = new File(path);
try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file))) {
outputStream.write(data1);
} catch (IOException e) {
e.printStackTrace();
} */
try {
ftp.connect("link.myjpl.com");
ftp.login("user", "password");
String path = "Images/test/"+filename+"."+ extension;
OutputStream out1 = ftp.storeFileStream(path);
out1.write(data1);
ftp.logout();
} catch (IOException e) {
e.printStackTrace();
}
return base64Image;
}
}
Try setting the fileType to FTP.BINARY_FILE_TYPE. Also as per the javadocs, to finalize the file transfer you must call completePendingCommand and check its return value to verify success.
See https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#storeFileStream(java.lang.String)

How to read file from network path?

Basic explanation:
I'm coding a simple java utility which will take xml file and convert it into html. All xml files have same structure and need to be converted into same looking HTML file so i chose to code it using BufferedReader and Writer, see code below.
I'm having following problem If i'm using file that is on local disk, than there is no problem and everything workes fine, but when i try to use file that is on connected shared network disk, code throws exception.
this is whole code
reading and writting file that is stored in project folder workes just fine and just as i want to, i'm only having problem with file stored on network disk.
public static void main(String[] args) {
String cestaKsuboruXml = "file.xml"; //workes fine
//this one throws error
// String cestaKsuboruXml = "\\172.27.20.38\eDesk\2017\0925\144f7d8d-3786-4858-95ef-bb853c41b713\1_PridelenieCislaPodania.xml";
//class which contains html code
sablonaJedna sablonaJedna = new sablonaJedna();
String fileName = null ;
String line = null;
StringBuilder text = new StringBuilder();
StringBuilder subject = new StringBuilder();
try {
FileReader fileReader = new FileReader(cestaKsuboruXml);
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(new FileInputStream(cestaKsuboruXml), "UTF-8"));
while ((line = bufferedReader.readLine()) != null) {
if (line.contains("<subject>")) {
subject.append(line);
}
if (!line.contains("<GeneralAgenda") && !line.contains("<subject>"))
{
text.append(line);
}
}
} catch (IOException ex) {
System.out.println("Exception");
}
String text2 = text.toString();
String subject2 = subject.toString();
subject2 = subject2.replace("<subject>", "");
subject2 = subject2.replace("</subject>", "");
text2 = text2.replace("<text>", "");
text2 = text2.replace("</text>", "");
text2 = text2.replace("</GeneralAgenda>", "");
try {
BufferedWriter writer = new BufferedWriter
(new OutputStreamWriter(new FileOutputStream("vvvaa.html", true), "UTF-8"));
writer.write(sablonaJedna.getSablonaCss() + sablonaJedna.getSablonaHtml() + subject2 +
"</span></div><div class=\"clear\"> </div><div><label class=\"labelVis\">Text: </label> <span class=\"contentVis wordwrap\">"
+ text2 + "</span></div><div class=\"clear\"> </div></div></div></body></html>"
);
writer.close();
} catch (IOException xx) {
System.out.println("Exception");
}
}
all i had to do was use this as a source:
String cestaKsuboruXml = "\\\\172.27.20.38\\eDesk\\2017\\0925\\144f7d8d-3786-4858-95ef-bb853c41b713\\1_PridelenieCislaPodania.xml";
so two more backslashes at the start of a link

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

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());

Categories