Write JSON Object to file- append not working - java

I'try to save my custom JSONObject into the file.Everything working correct but I can't append json into file.For example,If I click twice to save json,in my file I have one element.Here is a my source
public class TransactionFileManager {
public static final File path = Environment.
getExternalStoragePublicDirectory(Environment.getExternalStorageState() + "/myfolder/");
public static final File file = new File(path, "transaction1.json");
public static String read() {
String ret = null;
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
try {
String receiveString;
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString);
}
ret = stringBuilder.toString();
bufferedReader.close();
} catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
try {
file.createNewFile();
} catch (IOException ioe) {
ioe.printStackTrace();
}
e.printStackTrace();
}
return ret;
}
public static void writeToFile(JSONObject data) {
if (!path.exists()) {
path.mkdirs();
}
try {
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fOut);
outputStreamWriter.append(data.toString());
outputStreamWriter.close();
fOut.flush();
fOut.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
}
How I can append json object into my .json file.What's a wrong in my code
thanks

Related

How to write all JSON objects from a for loop into a text file using java

I am trying to save all my results from JSON into a text file. However, my for loop seems to be only saving the last result from the loop to the text file. It is obviously just re-writing the result each time into the file. I want to be able to save all the results from the for loop before it saves the file.
List<Status> statuses = null;
Query query = new Query("football");
query.setCount(100);
query.lang("en");
int i=0;
try {
QueryResult result = twitter.search(query);
ArrayList tweets = new ArrayList();
for( Status status : result.getTweets()){
System.out.println("#" + status.getUser().getScreenName() + ":" + status.getText());
String rawJSON = TwitterObjectFactory.getRawJSON(status);
String statusfile = "results.txt";
storeJSON(rawJSON, statusfile);
i++;
}
System.out.println(i);
}
catch(TwitterException e) {
System.out.println("Get timeline: " + e + " Status code: " + e.getStatusCode());
}
} catch (TwitterException e) {
if (e.getErrorCode() == 88) {
System.err.println("Rate Limit exceeded!!!!!!");
try {
long time = e.getRateLimitStatus().getSecondsUntilReset();
if (time > 0)
Thread.sleep(100);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}
private static void storeJSON(String rawJSON, String fileName) throws IOException {
FileOutputStream fos = null;
OutputStreamWriter osw = null;
BufferedWriter bw = null;
try {
fos = new FileOutputStream(fileName);
osw = new OutputStreamWriter(fos, "UTF-8");
bw = new BufferedWriter(osw);
bw.write(rawJSON);
bw.flush();
} finally {
if (bw != null) {
try {
bw.close();
} catch (IOException ignore) {
}
}
if (osw != null) {
try {
osw.close();
} catch (IOException ignore) {
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException ignore) {
}
}
}
}
}
The method at the bottom called storeJSON is where the work is being done.
Have you tried using a FileWriter with append mode ?
private static void storeJSON(String rawJSON, String fileName) throws IOException {
FileWriter fileWriter = null;
try
{
fileWriter = new FileWriter(fileName, true);
fileWriter.write(rawJSON);
fileWriter.write("\n");
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
} finally {
if(fileWriter!=null) {
fileWriter.close();
}
}
}

Client's BufferedInputStream.read() while loop never stops

I EDITED CODE
I'm making file transfer program with java
I have to send 21 files.
my code stops at Client's while loop in run()
(It doesn't print "file receive complete") <- see run() in Client
Server's CODE
class SendFileThread extends Thread {
private ServerSocket fileTransferServerSocket;
private Socket fileTransferSocket;
private BufferedReader requestReader;
private PrintWriter requestAnswerer;
private BufferedOutputStream fileWriter;
private int fileTransferPort = 12345;
public SendFileThread() {
try {
fileTransferServerSocket = new ServerSocket(fileTransferPort);
fileTransferSocket = fileTransferServerSocket.accept();
requestReader = new BufferedReader(new InputStreamReader(fileTransferSocket.getInputStream()));
fileWriter = new BufferedOutputStream(fileTransferSocket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void CloseTransferStream() {
try {
requestAnswerer.close();
requestReader.close();
fileWriter.close();
fileTransferSocket.close();
fileTransferServerSocket.close();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
public void SendFile(String filename) {
try {
File file = new File(CLIENT_PATH + "/" + filename);
BufferedInputStream fileReader = new BufferedInputStream(new FileInputStream(file));
int packet;
while((packet = fileReader.read()) != -1)
fileWriter.write(packet);
fileWriter.flush();
fileReader.close();
}
catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
//System.out.print(filename + " send complete (" + count + " times)");
}
public void ListenForRequester() {
try {
String input;
while((input = requestReader.readLine()) != null) {
if(input.equals("request file")) {
SendFile(requestReader.readLine());
}
else if(input.equals("end transfer"))
break;
else {
System.out.println("Something wrong");
}
}
}
catch(IOException ioe) {
ioe.getStackTrace();
}
}
public void run() {
ListenForRequester();
CloseTransferStream();
}
}
Client's CODE
class ReceiveFileThread extends Thread {
private Socket fileTransferSocket;
private int fileTransferPort = 12345;
private BufferedInputStream fileReader;
private PrintWriter fileRequester;
public ReceiveFileThread() {
try {
fileTransferSocket = new Socket(serverIP, fileTransferPort);
fileRequester = new PrintWriter(fileTransferSocket.getOutputStream(), true);
fileReader = new BufferedInputStream(fileTransferSocket.getInputStream());
}
catch (UnknownHostException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
public void CloseTransferStream() {
try {
fileRequester.close();
fileReader.close();
fileTransferSocket.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
public synchronized void RequestFile(String filename) {
fileRequester.println("request file");
fileRequester.println(filename);
}
public synchronized void SendEndMsg() {
fileRequester.println("end transfer");
}
public void run() {
for(int i = 0;i < fileList.size();i++) {
String filename = (String)fileList.get(i);
RequestFile(filename);
try {
BufferedOutputStream fileWriter = new BufferedOutputStream(new FileOutputStream(new File(PROGRAM_PATH + "/" + filename)));
int packet = 0;
while((packet = fileReader.read()) > -1)
fileWriter.write(packet);
System.out.println("file receive complete");
fileWriter.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
SendEndMsg();
CloseTransferStream();
}
}
It became 5 days that this error bothers me :(
Could anyone save me from this error?
Closing the socket's output stream will close the socket, In order to send multiple files you will have to make a couple of changes.
Server:
Before you start to send a file, send that file's length.
Client:
After you receive the file's length start to read that many bytes from the input stream and save them to a file, when you're done read the next file's length.

Java: Read/Write a File and more

I made a Class with 2 Methods which should handle either Writing in a file or reading from it.
Ive came up with something like this:
package YBot;
import java.io.*;
public class FollowerChecker {
public static StringBuilder sb;
static String readFile(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}
public static void Writer() {
FileWriter fw = null;
try {
fw = new FileWriter("donottouch.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
StringWriter sw = new StringWriter();
sw.write(TwitchStatus.totalfollows);
try {
fw.write(sw.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Now My Question is:
How can i add the function to create the "donottouch.txt" file if it doesnt exist already or if its empty to write "0" in it? when my program starts it will read the file for a number and later, if the number is changed it will rewrite it. so it would be the best that as soon it trys to read and its not there, it creates it right then and reread it. hope some1 can give me any examples =)
Here is how I handled it:
public static boolean checkIfExists(String path) {
if (!new File(path).exists()) {
return false;
} else {
return true;
}
}
public static String readFile(String file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader (file));
String line;
StringBuilder sb = new StringBuilder();
while( ( line = reader.readLine() ) != null) {
sb.append( line );
}
reader.close();
return sb.toString();
}
public static void writeFile(String path) throws FileNotFoundException,
UnsupportedEncodingException {
PrintWriter writer = new PrintWriter(path, "UTF-8");
writer.println("0");
writer.close();
return;
}
public static void main(String args[]) {
/*Gets absolute path to your project folder, assuming that is where
* you are storing this text file. Otherwise hard code your path
* accordingly.
*/
File file = new File("");
String fileGet = file.getAbsolutePath();
StringBuilder sb = new StringBuilder();
String path = sb.append(fileGet.toString() + "/donottouch.txt").toString();
String result=null;
if(!checkIfExists(path)) {
try {
writeFile(path);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
System.out.println("File created: 'donottouch.txt'");
} else {
try {
result = readFile(path);
} catch (IOException e) {
e.printStackTrace();
}
if( result.length() == 0 ) {
try {
writeFile(path);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
System.out.println("File amended: 'donottouch.txt'");
}
System.out.println("File exists: 'donottouch.txt'");
}
}
Obviously I created a main class and did all of this outside of a class, unlike you, but it should be very simple to integrate. It is predicated on the presumption that you are storing your "donottouch.txt" in the source file of the project, however you can easily change the piece of code that grabs your absolute path to the hardcoded path of the folder in which you are looking. Hope this helps!

Parse a Path from Java program

Have a file on specified path /foo/file-a.txt and that file contains a path of another file
file-a.txt contains: /bar/file-b.txt this path at line one. need to parse the path of file-b.txt and zip that file and move that zipped file to another path /too/ from my Java code.
I been till the below code then i m stuck.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Reader
{
public static void main(String[] args)
{
BufferedReader br = null;
try
{
String CurrentLine;
br = new BufferedReader(new FileReader("/foo/file-a.txt"));
while ((CurrentLine = br.readLine()) != null)
{
System.out.println(CurrentLine);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (br != null)br.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
}
am getting path as text, help would be appreciated. Thanks in advance
For the actual zipping of the file, this page may be of help.
As a general note, this code will replace the current existing zip file.
public class TestZip02 {
public static void main(String[] args) {
try {
zip(new File("TextFiles.zip"), new File("sample.txt"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void zip(File zip, File file) throws IOException {
ZipOutputStream zos = null;
try {
String name = file.getName();
zos = new ZipOutputStream(new FileOutputStream(zip));
ZipEntry entry = new ZipEntry(name);
zos.putNextEntry(entry);
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
byte[] byteBuffer = new byte[1024];
int bytesRead = -1;
while ((bytesRead = fis.read(byteBuffer)) != -1) {
zos.write(byteBuffer, 0, bytesRead);
}
zos.flush();
} finally {
try {
fis.close();
} catch (Exception e) {
}
}
zos.closeEntry();
zos.flush();
} finally {
try {
zos.close();
} catch (Exception e) {
}
}
}
}
For moving the file, you can use File.renameTo, here's an example.
Hope this helps!

I want know how I can write my InputStream content to an XML file (android)

Hey I have the following code:
import java.net.*;
import java.io.*;
class OpenStreamTest {
public static void main(String args[]) {
try {
URL yahoo = new URL("http://www.yahoo.com/");
DataInputStream dis;
String inputLine;
dis = new DataInputStream(yahoo.openStream());
while ((inputLine = dis.readLine()) != null) {
System.out.println(inputLine);
}
dis.close();
} catch (MalformedURLException me) {
System.out.println("MalformedURLException: " + me);
} catch (IOException ioe) {
System.out.println("IOException: " + ioe);
}
}
}
How can i save the source code i get from this to a XML file? Please help
Create a Connection:
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet("http://www.google.com");
HttpResponse response = httpclient.execute(httppost);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
InputStream is = buf.getContent();
Put inputstream in a buffer and read it:
BufferedReader r = new BufferedReader(new InputStreamReader(is2));
total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
Then put it in the file:
File file = new File("/sdcard", "report.xml");
if(!file.exists()){
file.createNewFile();
}
StringBuilder temp = null;
while ((inputLine = dis.readLine()) != null) {
temp.append(inputLine);
}
FileWriter fw = new FileWriter(file);
fw.write(temp.toString());
fw.flush();
Hope this helpes
Here is an example, where "iso" is you InputSrteam
try {
final File file = new File("/sdcard/filename.xml");
final OutputStream output = new FileOutputStream(file);
try {
try {
final byte[] buffer = new byte[1024];
int read;
while ((read = iso.read(buffer)) != -1)
output.write(buffer, 0, read);
output.flush();
}
finally {
output.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
iso.close();
System.out.println("saved");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Categories

Resources