Uncomppresed GZIP FILE WRITTEN BY WRITER - java

I have this code that compresses a string and write to a streamwritter
FileOutputStream output = new FileOutputStream(outPutFilePath.toFile());
try {
Writer writer = new OutputStreamWriter(new GZIPOutputStream(output), "UTF-8");
try {
writer.write(String.valueOf(stringByteArray));
} finally {
writer.close();
}
} finally {
output.close();
}
How can I convert back my string?

Related

Copying and appending Strings to json file in Android Studio

I have list of json files as below:
At the moment, T.json file is empty. All the other files already have some text. What I need is to create something like this:
1.At the beginning of the T.json file add sth like
{
"T": [
2.Copy text from e.g. T_Average.json and T_Easy.json to T.json file
3.At the end of T.json file add this:
]
}
So at the end of program execution I need to have in my T.json sth like:
{
"T": [
text from T_Average.json
text from T_Easy.json
]
}
So how can I add text from 1st and 3rd step to the file?
And how can I copy everything from other files to T.json file?
I have already tried some solutions like this:
try(FileWriter fw = new FileWriter("T.json", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.println("the text");
out.println("more text");
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
or like this one:
try {
String data = " This is new content";
File file = new File(FILENAME);
if (!file.exists()) {
file.createNewFile();
}
fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
bw.write(data);
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
but all the time, after line with fw = new FileWriter() it was jumping right to the catch clause.
So one more time:
How can I add text from 1st and 3rd step to the file?
And how can I copy everything from other files to T.json file?
Thanks :)
Try
1. Add following methods getJsonFromAssetFile and writeFile to your code
2. Read json file
String content = getJsonFromAssetFile("T_Difficult.json");
3 Create final json (as mentioned)
JSONObject finalJson = new JSONObject();
try {
JSONObject jsonObject = new JSONObject(content);
JSONArray jsonArray = new JSONArray();
jsonArray.put(jsonObject);
finalJson.put("T", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
4. Write final json to file
writeFile(finalJson.toString().getBytes());
writeFile
public static void writeFile(byte[] data, File file) throws IOException {
BufferedOutputStream bos = null;
try {
FileOutputStream fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(data);
}
finally {
if (bos != null) {
try {
bos.flush ();
bos.close ();
}
catch (Exception e) {
}
}
}
}
getJsonFromAssetFile
public static String getJsonFromAssetFile(Context context, String jsonFileName) {
String json = null;
try {
InputStream is = context.getAssets().open(jsonFileName);
int size = is.available ();
byte[] buffer = new byte[size];
is.read (buffer);
is.close ();
json = new String(buffer, "UTF-8");
}
catch(IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
NOTE: Read json asset file using getJsonFromAssetFile method and Write file on internal/external storage and provide proper path to writeFile method

Java BufferedWriter and OutputStream .close() method

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

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

Extremely weird NullPointerException when reading in a File Android

Here is the code:
Thread clientThread = new Thread() {
#Override
public void run() {
try {
client = new Client();
quest = client.readFile();
Log.v("Client string", quest);
//File file = new File(myContext.getFilesDir(), "questionnaire.xml");
//BufferedWriter bw = new BufferedWriter(new FileWriter(file));
//bw.write(quest);
File tempFile = File.createTempFile("questionnaire", ".xml");
FileOutputStream fout = new FileOutputStream(tempFile);
PrintStream out = new PrintStream(fout);
out.println(quest);//InputStream stream = new ByteArrayInputStream(quest.getBytes("UTF-8"));
//getResources().op
try {
Serializer serializer = new Persister();
responseToQuestionnaire = serializer.read(ResponseToQuestionnaire.class, tempFile);
}
catch(Exception e) {}
Log.v("Let's seeeeee",responseToQuestionnaire.getQuestionnaireTemplate().toString());
} catch (Exception e1) {
e1.printStackTrace();
}
// try {
// OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
// openFileOutput(currentQuestionnaire.getName(),
// Context.MODE_PRIVATE));
// outputStreamWriter.write(client.readFile());
// outputStreamWriter.close();
// } catch (IOException e) {
// Log.e("Exception", "File write failed: " + e.toString());
// }
}
};
clientThread.start();
The code throws a Null Pointer exception even when quest is a full length string that prints in log perfectly fine. I tried multiple ways of saving the file but SimpleXML doesn't serialize string... only XML files.
Buffered streams don't necessarily write the data until they have to. Try closing the output stream before you call the read() method.

Printing on Printronix T5000r over ethernet using Java

I have a problem with printing on this specific printer.
public void print(String fileName, String printerIp) {
try {
BufferedReader streamIn = new BufferedReader(new FileReader(fileName));
String line;
Socket socket = new Socket(printerIp, 9100);
Writer writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
while ((line = streamIn.readLine()) != null) {
writer.write(line);
}
writer.flush();
socket.close();
streamIn.close();
}
The situation looks like everything is fine but the printer do not print, when I use other program to print everything works fine.
Any thoughts ?
The solution is to write whole file to the printer.
public void printFile(File file, String printerIp) throws PrintException, IOException {
Socket socket = new Socket(printerIp, 9100);
FileInputStream fileInputStream = new FileInputStream(file);
byte [] mybytearray = new byte [(int)file.length()];
fileInputStream.read(mybytearray,0,mybytearray.length);
OutputStream outputStream = socket.getOutputStream();
outputStream.write(mybytearray,0,mybytearray.length);
//Curious thing is that we have to wait some time to make more prints.
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
outputStream.flush();
outputStream.close();
socket.close();
fileInputStream.close();
}

Categories