Binary data in String representation to PDF file - java

So I'm receiving a response from a service which is a byte array representation of pdf file in String like below:
response.pdfStream = "JVBERi0xLjQKJcfsj6IKNSAwIG9iago8PC9MZW5ndGggNiAwIFIvRmlsdGVyIC9GbGF0ZURlY29kZT4+CnN0cmVhbQp4nK1aS3MbxxG+45Qql+9zcQlIEat57wxzAgJIcviQTYCqKGIOKwEWN3hJIKgU+Wt88U9I/kKuOflk6OqrTz4RrHyzu7MASCzHUkypCtBOT3dPT39fdy/1ntBIGkLdH//lzaT2+CQmby9q7wnjUmUPxXrJkM6s9u3mIuOZRLZqd68ylS8zunudx8U6q9Bui3W+e12xYl3sXtcPuxerB5dN/OCytQ+fnbGH13kgduJh75h82D2mfPBkhUDso6cqBIwICFj1sACncUCA2YCACDjJZcBJrkJO6pCTcchJG3BS0ICTggWcFDzgpBABJ4UKOalDTsYhJ03ISRtwUrKAk5IHnJQi4KSUASelCjkZAo4MAUeGgKNCwFEh4KgQcFQIOCoEHBUCjgoBR4WAo0PA0SHg6BBwdAg4OgQcHQKODgFHh4CjQ8CJQ8CJQ8CJQ8CJQ8CJQ8CJQ8CJQ8CJQ8AxIeCYEHBMCDgmBBwTAo4JAceEgGNCwLEh4NgQcGwIODYEHBsCjg0Bx4aAY0PAsSHgMBpCDqMh6DAawg6jIfAwGkIPo8GGj..."
I need to convert this to absolute byte array and then create pdf file with it to open.
Tried this:
byte[] pdfStream = response.pdfStream.getBytes(Charsets.UTF_8);
InputStream inputStream = new ByteArrayInputStream(pdfStream);
File file = null;
try {
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), filename);
Logger.debug("createFile: "+file.getAbsolutePath());
OutputStream outputStream = new FileOutputStream(file);
IOUtils.copy(inputStream, outputStream);
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
getMainActivity().startActivity(intent);
} catch (Exception e) {
Logger.printStackTrace(e);
}

With this code snippet it was very easy to convert a Base64 encoded String to a pdf-File.
The String is read from the input.txt file.
public void convertInputFile() {
try {
convertToPDF("/home/input.txt");
} catch (IOException e) {
}
}
private void convertToPDF(String inputFilePath) throws IOException {
byte[] byteArray = Files.toByteArray(new File(inputFilePath));
byte[] bytes = Base64.decodeBase64(byteArray);
DataOutputStream os = new DataOutputStream(new FileOutputStream("/home/output.pdf"));
os.write(bytes);
os.close();
}

Related

How to download chosen file from ftp-server using java? [duplicate]

With this code iI always get a empty file.
What I have to do with it?
login is always true. (ofc, here is not real password)
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import java.io.*;
public class Logs {
public static void main(String[] args) {
FTPClient client = new FTPClient();
try {
client.connect("myac.cs-server.pro", 121);
boolean login = client.login("a3ro", "passWordIsSecret");
System.out.println(login);
String remoteFile1 = "myac_20150304.log";
File downloadFile1 = new File("C:\\Users\\Aero\\Desktop\\test\\myac.log");
OutputStream outputStream1 =
new BufferedOutputStream(new FileOutputStream(downloadFile1));
boolean success = client.retrieveFile(remoteFile1, outputStream1);
System.out.println(success);
outputStream1.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Use FileOutputStream:
String filename = "test.txt";
FileOutputStream fos = new FileOutputStream(filename);
client.retrieveFile("/" + filename, fos);
Use something like this:
InputStream inputStream = client.retrieveFileStream(remoteFileNameHere);
To retrieve the remote file input stream.
Then you can use to copy the stream to desired file:
FileOutputStream out = new FileOutputStream(targetFile);
org.apache.commons.io.IOUtils.copy(in, out);

Base64 decode and uncompress a string

I have a String which is first zipped (not gzip) and then base64 encoded.
I want to have the plain text again. Following code
private void decode_decompress(String string) {
byte[] decodedBytes = Base64.decodeBase64(string.getBytes());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Inflater decompresser = new Inflater(true);
InflaterOutputStream inflaterOutputStream = new InflaterOutputStream(stream, decompresser);
try {
inflaterOutputStream.write(decodedBytes);
inflaterOutputStream.close();
byte[] output2 = stream.toByteArray();
logger.info("Data: {}", output2.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
throws an exception:
java.util.zip.ZipException: invalid stored block lengths
at java.util.zip.InflaterOutputStream.write(InflaterOutputStream.java:273)
at java.io.FilterOutputStream.write(FilterOutputStream.java:97)
at de.martinm.tools.EBICS.DSTools.decode_decompress(DSTools.java:87)
at de.martinm.tools.EBICS.DSTools.process(DSTools.java:77)
at de.martinm.tools.EBICS.DSTools.main(DSTools.java:100)
I guess, I'm mixing up again input/output inflate/deflate
Here is the data which is compressed and base64 encoded:
eJx1U2tzqjAQ/SsO96NTw1PBQTr4qlgtyqvVL3cihEehiSYg1l9/rd46dZx+y549Ocme3dUfDx9FY48oywjucUKL5xoIhyTKcNLjfG/8oHINVkIcwYJg1OMw4R4N3c0SDMuKokW1eUafNo0QHcISNk5qmPW4tCy3XQDqum6hTRayFqEJcHle4C6MbnRLqqUzQ+R5HvAaOHEiliV/vtlnjR5XUdw90S5hd8Lz8jfhwLJf9ATwNp+5YYo+4EOGvyoJ0ekWy7rsDM5ICMtz7b/+uXH/Ljgf/7JvG1oHFnF3tlg4JoZ+OQewqJChR6zruOZNPCdRVVTMMOebJcxHZRJ1kqeDJJqfR6IQJDdngt1cBt5ncYKnO8d99Tp9gYoweT2O40BUatURhWKZvVHV7E8102XHXTDN5ZI1vZyX6KKeSm+SmK9VlQZ5nZeKvd8X7aPUmRztxdp8rtaZom1kJlsRqsK95RSS7RJ7AYOQbg6S2vZXrjWA6S5vqzlWYCG/z947YgXjcOasFuF8/JKs34nngCGYIVBukJd9jLHftuQSmfV6LJFg2CQrU5Ze4qJYpR1/b5qD2MaOvSv27Z1PV4GA+p1U1IDFWLJaifGEKmGKxZ3lq5Ox0EHb1G++JvGIpaSayxYd9J2kfO7nhXiw4XYYD3fyJsbC8kmDVv2iJZqqaAtnn/d08MPkL8NHh+1plHFpmEtzcM5ekXN00yBw075rg4PLxhgmz7d1cAf/gG5GAdISI2oNjVHfGried5K/QrrPfqYUHfwH7sSu62b8A39iR+Y=
This solved the issue:
private void decode_decompress(String string) {
byte[] decodedBytes = Base64.decodeBase64(string);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Inflater decompresser = new Inflater(false);
InflaterOutputStream inflaterOutputStream = new InflaterOutputStream(stream, decompresser);
try {
inflaterOutputStream.write(decodedBytes);
inflaterOutputStream.close();
String data = stream.toString();
logger.info("Data: {}", data);
} catch (IOException e) {
logger.error(string, e);
}
}

Read and Write text file from my own class in Android Studio

I have been trying to create a class called TextFileReaderWriter I want to use the getters and setters to read and write to a text file in such a way that I can call the class and the method from anywhere in the program by simply using setfileContents(somestring) and somestring = getfileContents() something like this
example:
TextFileReaderWriter trw = new TextFileReaderWriter();
trw.setfileContents(somestring); //this would write 'somestring' to the text file.
String somestring = trw.getfileContents(); //this would return 'somestring' from the text file.
Here's what I have so far but it writes nothing to the file:
public class TextFileReaderWriter extends Activity{
String fileContents;
Context context;
String TAG = "MYTAG";
public TextFileReaderWriter(String fileContents, Context context) {
this.fileContents = fileContents;
this.context = context;
}
public String getFileContents() {
return fileContents;
}
public void setFileContents(String fileContents) {
this.fileContents = fileContents;
FileOutputStream fos = null;
try {
fos = context.openFileOutput("UserInputStore", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
OutputStreamWriter osw = new OutputStreamWriter(fos);
try {
osw.write(fileContents);
Log.d(TAG, fileContents);
} catch (IOException e) {
e.printStackTrace();
}
}
}
You don't need the OutputStreamWriter--FileOutputStreamwill do the trick just fine.
//what you had before
FileOutputStream fos = null;
try {
fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//use just the file output stream to write the data
//data here is a String
if (fos != null) {
try {
fos.write(data.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Method to save data on disk :
protected static void saveDataOnDisk(String data) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
ObjectOutput objectOutput = new ObjectOutputStream(byteArrayOutputStream);
objectOutput.writeObject(data);
byte[] buffer = byteArrayOutputStream.toByteArray();
File loginDataFile = (new File(filePath)); // file path where you want to write your data
loginDataFile.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(loginDataFile);
fileOutputStream.write(buffer);
fileOutputStream.close();
objectOutput.flush();
objectOutput.close();
byteArrayOutputStream.flush();
byteArrayOutputStream.close();
Log.i(“SAVE”, ”———————-DONE SAVING”);
} catch(IOException ioe) {
Log.i(“SAVE”, “———serializeObject|”+ioe);
}
}
Method to fetch data from disk:
private static Object getDataFromDisk() {
try {
FileInputStream fileInputeStream = new FileInputStream(FilePath);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputeStream);
Object data = (Object) objectInputStream.readObject();
objectInputStream.close();
fileInputeStream.close();
return dataModel;
} catch (Exception error) {
Log.i(“FETCH”, ”—-getDataFromDisk———ERROR while reading|” + error);
}
return null;
}

java write records to new line of file

every time the code runs i want the new record to be added to a new line
as it is when a new record is added it will write over previous line
private void writeFile() {
String FILENAME = g.getText();
String content = results;
FileOutputStream fos = null;
try {
fos = openFileOutput(FILENAME, MODE_PRIVATE);
fos.write(content.getBytes());
Toast.makeText(getApplicationContext(), "File Saved", 0).show();
} catch (IOException e) {
e.printStackTrace();
}
}
You need to write the "newline" character as well when writing data:
private void writeFile() {
String FILENAME = g.getText();
String content = results;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(content.getBytes());
fos.write(System.getProperty("line.separator"));
} catch (IOException e) {
e.printStackTrace();
}
}
But be careful with writing binary data like this. It's better to use e. g. BufferedWriter to write string data:
BufferedWriter writer = new BufferedWriter(new FileWriter("filename"));
writer.write("Hello world!");
writer.newLine();

saving JSON file from url in Internal Storage

for my android app i need to download a JSON from a url into android's internal storage and then read from it. I think that the best way to save it as byte[] into internal storage although i have some problems here is what i've written so far
File storage = new File("/sdcard/appData/photos");
storage.mkdirs();
JSONParser jParser = new JSONParser();
// getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url1);
//transforming jsonObject to byte[] and store it
String jsonString = json.toString();
byte[] jsonArray = jsonString.getBytes();
String filen = "jsonData";
File fileToSaveJson = new File("/sdcard/appData",filen);
FileOutputStream fos;
fos = new FileOutputStream(fileToSaveJson);
fos = openFileOutput(filen,Context.MODE_PRIVATE);
fos.write(jsonArray);
fos.close();
//reading jsonString from storage and transform it into jsonObject
FileInputStream fis;
File readFromJson = new File("/sdcard/appData/jsonData");
fis = new FileInputStream(readFromJson);
fis = new FileInputStream(readFromJson);
InputStreamReader isr = new InputStreamReader(fis);
fis.read(new byte[(int)readFromJson.length()]);
but it won't open the file in order to read it
private void downloadAndStoreJson(String url,String tag){
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
String jsonString = json.toString();
byte[] jsonArray = jsonString.getBytes();
File fileToSaveJson = new File("/sdcard/appData/LocalJson/",tag);
BufferedOutputStream bos;
try {
bos = new BufferedOutputStream(new FileOutputStream(fileToSaveJson));
bos.write(jsonArray);
bos.flush();
bos.close();
} catch (FileNotFoundException e4) {
// TODO Auto-generated catch block
e4.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
jsonArray=null;
jParser=null;
System.gc();
}
}
public static File createCacheFile(Context context, String fileName, String json) {
File cacheFile = new File(context.getFilesDir(), fileName);
try {
FileWriter fw = new FileWriter(cacheFile);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(json);
bw.close();
} catch (IOException e) {
e.printStackTrace();
// on exception null will be returned
cacheFile = null;
}
return cacheFile;
}
public static String readFile(File file) {
String fileContent = "";
try {
String currentLine;
BufferedReader br = new BufferedReader(new FileReader(file));
while ((currentLine = br.readLine()) != null) {
fileContent += currentLine + '\n';
}
br.close();
} catch (IOException e) {
e.printStackTrace();
// on exception null will be returned
fileContent = null;
}
return fileContent;
}
public void writeObjectInInternalStorage(Context context, String filename, Object object) throws IOException {
FileOutputStream fileOutputStream = context.openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(object);
objectOutputStream.close();
fileOutputStream.close();
}
public Object readObjectFromInternalStorage(Context context, String filename) throws IOException, FileNotFoundException, ClassNotFoundException{
FileInputStream fileInputStream = context.openFileInput(filename);
return new ObjectInputStream(fileInputStream).readObject();
}
use these methods, call readObjectFromInternalStorage() and cast it to JSON String.

Categories