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.
Related
My use case is this: when the client clicks download on a pdf, I want to edit/write some text on to the pdf using Itext pdf editor, then zip the pdf then let it download, All during the stream. I am aware of memory issue if the pdf is large etc. which won't be an issue since its like 20-50kb. I have the zipping during the stream before downloading working using byte array, now have to make the pdfeditor method also run before zipping, add some text then let the download happen.
Here is my code so far:
public class zipfolder {
public static void main(String[] args) {
try {
System.out.println("opening connection");
URL url = new URL("http://gitlab.itextsupport.com/itext/sandbox/raw/master/resources/pdfs/form.pdf");
InputStream in = url.openStream();
// FileOutputStream fos = new FileOutputStream(new
// File("enwiki.png"));
PdfEditor writepdf = new PdfEditor();
writepdf.manipulatePdf(url, dest, "field"); /// where i belive i
/// should execute the
/// editor function ?
File f = new File("test.zip");
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(f));
ZipEntry entry = new ZipEntry("newform.pdf");
zos.putNextEntry(entry);
System.out.println("reading from resource and writing to file...");
int length = -1;
byte[] buffer = new byte[1024];// buffer for portion of data from
// connection
while ((length = in.read(buffer)) > -1) {
zos.write(buffer, 0, length);
}
zos.close();
in.close();
System.out.println("File downloaded");
} catch (Exception e) {
System.out.println("Error");
e.printStackTrace();
}
}
}
public class PdfEditor {
public String insertFields (String field, String value) {
return field + " " + value;
// System.out.println("does this work :" + field);
}
// public static final String SRC = "src/resources/source.pdf";
// public static final String DEST = "src/resources/Destination.pdf";
//
// public static void main(String[] args) throws DocumentException,
// IOException {
// File file = new File(DEST);
// file.getParentFile().mkdirs();
// }
public String manipulatePdf(URL src, String dest, String field) throws Exception {
System.out.println("test");
try {
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
AcroFields form = stamper.getAcroFields();
Item item = form.getFieldItem("Name");
PdfDictionary widget = item.getWidget(0);
PdfArray rect = widget.getAsArray(PdfName.RECT);
rect.set(2, new PdfNumber(rect.getAsNumber(2).floatValue() + 20f));
String value = field;
form.setField("Name", value);
form.setField("Company", value);
stamper.close();
} catch (Exception e) {
System.out.println("Error in manipulate");
System.out.println(e.getMessage());
throw e;
}
return field;
}
}
So playing with ByteArrayOutputStream, finally got it work. passing the input stream to 'manipulatepdf' and returning 'bytedata'.
public ByteArrayOutputStream manipulatePdf(InputStream in, String field) throws Exception {
System.out.println("pdfediter got hit");
ByteArrayOutputStream bytedata = new ByteArrayOutputStream();
try {
PdfReader reader = new PdfReader(in);
PdfStamper stamper = new PdfStamper(reader, bytedata);
AcroFields form = stamper.getAcroFields();
Item item = form.getFieldItem("Name");
PdfDictionary widget = item.getWidget(0);
PdfArray rect = widget.getAsArray(PdfName.RECT);
rect.set(2, new PdfNumber(rect.getAsNumber(2).floatValue() + 20f));
String value = field;
form.setField("Name", value);
form.setField("Company", value);
stamper.close();
} catch (Exception e) {
System.out.println("Error in manipulate");
System.out.println(e.getMessage());
throw e;
}
return bytedata;
}
public String editandzip (String data, String Link) {
try {
System.out.println("opening connection");
URL url = new URL(Link);
InputStream in = url.openStream();
System.out.println("in : "+ url);
//String data = "working ok with main";
PdfEditor writetopdf = new PdfEditor();
ByteArrayOutputStream bao = writetopdf.manipulatePdf(in, data);
byte[] ba = bao.toByteArray();
File f = new File("C:/Users/JayAcer/workspace/test/test.zip");
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(f));
ZipEntry entry = new ZipEntry("newform.pdf");
entry.setSize(ba.length);
zos.putNextEntry(entry);
zos.write(ba);
zos.close();
in.close();
System.out.println("File downloaded");
} catch (Exception e) {
System.out.println("Error");
e.printStackTrace();
}
return data;
}
}
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();
}
I'm new in java and there is a question about BufferedWriter and OutputStream closing.
I have some logic, where it is inconvenient to use try-with-resources:
public static void writeFile(String fileName, String encoding, String payload) {
BufferedWriter writer = null;
OutputStream stream = null;
try {
boolean needGzip = payload.getBytes(encoding).length > gzipZize;
File output = needGzip ? new File(fileName + ".gz") : new File(fileName);
stream = needGzip ? new GZIPOutputStream(new FileOutputStream(output)) : new FileOutputStream(output);
writer = new BufferedWriter(new OutputStreamWriter(stream, encoding));
writer.write(payload);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
writer.close();
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
So, i have to close all resources by myself. Should i close OutputStream AND BufferedWriter? Or it is ok to close just BufferedWriter?
Is everything ok with my code?
No, Leave it to Java, let it handle it:
public static void writeFile(String fileName, String encoding,
String payload) {
boolean needGzip = payload.getBytes(Charset.forName(encoding)).length > gzipZize;
File output = needGzip ? new File(fileName + ".gz")
: new File(fileName);
try (OutputStream stream = needGzip ? new GZIPOutputStream(
new FileOutputStream(output)) : new FileOutputStream(output);
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(stream, encoding))) {
writer.write(payload);
} catch (IOException e) {
e.printStackTrace();
}
}
It is OK to just close the BufferedWriter. If you follow the Javadoc you will see that it closes all nested streams.
If you close BufferedWriter its stream will be closed too but BufferedWriter and OutputStream both implements Closeable. So if you want you can just use try with resource to handle the close for you
for example :
public static void writeFile(String fileName, String encoding, String payload) {
File output = new File(fileName);
try (OutputStream stream = new FileOutputStream(output);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream, encoding))) {
writer.write(payload);
} catch (IOException e) {
e.printStackTrace();
}
}
Edit: Added getStream to check if it needs gzip stream or no
Note: This answer is just an "update" of your code, i'm not sure what are you trying to do in general, so it may not be the best solution for your program
public static void writeFile(String fileName, String encoding, String payload) {
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(getStream(fileName, encoding, payload), encoding))) {
writer.write(payload);
} catch (IOException e) {
e.printStackTrace();
}
}
public static OutputStream getStream(String fileName, String encoding, String payload) throws IOException {
boolean needGzip = payload.getBytes(encoding).length > gzipZize;
File output = needGzip ? new File(fileName + ".gz") : new File(fileName);
return needGzip ? new GZIPOutputStream(new FileOutputStream(output)) : new FileOutputStream(output);
}
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;
}
I have got links like this link, which directly ask for the filename to save with, and start downloading in the browser.
How can I download or save this file programmatically?
I tried with the following method:
static void DownloadFile(String url, String fileName) throws MalformedURLException, IOException
{
url = "http://dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=DESCRIBE+<"+ url +">&format=text%2Fcsv";
URL link = new URL(url); //The file that you want to download
InputStream in = new BufferedInputStream(link.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(response);
fos.close();
System.out.println("Finished");
}
but this save the file having only the first line as ""subject","predicate","object"
" and not the complete file.
EDIT:
As suggested in an answer I tried the following, but that too gave only the first line of the file:
static void DownloadFile(String s_url, String fileName) throws MalformedURLException, IOException
{
s_url = "http://dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=DESCRIBE+<"+ s_url +">&format=text%2Fcsv";
//url = "http://dbpedia.org/data/Sachin_Tendulkar.rdf";
try {
URL url = new URL(s_url); //The file that you want to download
// read text returned by server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
PrintWriter out = new PrintWriter(fileName);
String line;
while ((line = in.readLine()) != null) {
out.println(line);
}
in.close();
out.close();
}
catch (MalformedURLException e) {
System.out.println("Malformed URL: " + e.getMessage());
}
catch (IOException e) {
System.out.println("I/O Error: " + e.getMessage());
}
System.out.println("Finished");
}
EDIT:
I tried with Apache FileUtils too, but that too gave only the first line of the file.
static void DownloadFile(String s_url, String fileName) throws MalformedURLException, IOException
{
s_url = "http://dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=DESCRIBE+<"+ s_url +">&format=text%2Fcsv";
URL url = new URL(s_url); //The file that you want to download
FileUtils.copyURLToFile(url, new File(fileName));
System.out.println("Finished");
}
if you want to download a file, Apache Commons have just what you are looking for, works great!
org.apache.commons.io.FileUtils.copyURLToFile(new URL("URL")), new File("path/to/file"));
if the url returns text, you can try something like this:
try {
URL url = new URL("http://www.google.com:80/");
// read text returned by server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
PrintWriter out = new PrintWriter("filename.txt");
String line;
while ((line = in.readLine()) != null) {
out.println(line);
}
in.close();
out.close();
}
catch (MalformedURLException e) {
System.out.println("Malformed URL: " + e.getMessage());
}
catch (IOException e) {
System.out.println("I/O Error: " + e.getMessage());
}