# How can we read & write a file using Gson streaming API in Java?

JavaJSONObject Oriented ProgrammingProgramming

We can read and write a file using Gson streaming API and it is based on sequential read and write standard. The JsonWriter and JsonReader are the core classes built for streaming write and read in Streaming API. The JsonWriter writes a JSON encoded value to a stream, one token at a time. The stream includes both literal values (strings, numbers, booleans, and nulls) as well as begin and end delimiters of objects and arrays and JsonReader reads a JSON encoded value as a stream of tokens. This stream includes both literal values (strings, numbers, booleans, and nulls) as well as the begin and end delimiters of objects and arrays. The tokens are traversed in depth-first order, the same order that they appear in the JSON document.

## Write to a file using JsonWriter

### Example

import java.io.*;
public class JsonWriterTest {
public static void main(String args[]) {
JsonWriter writer;
try {
writer = new JsonWriter(new FileWriter("input.json"));
writer.beginObject();
writer.name("age").value(25);
writer.name("technologies");
writer.beginArray();
writer.value("Java");
writer.value("Scala");
writer.value("Python");
writer.endArray();
writer.endObject();
writer.close();
System.out.println("Data write to a file successfully");
} catch(Exception e) {
e.printStackTrace();
}
}
}

### Output

Data write to a file successfully


### Example

import java.io.*;
public static void main(String args[]) {
try {
if(name.equals("name")) {
} else if(name.equals("age")) {
} else if(name.equals("technologies")) {
}
} else {
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
}

### Output

Adithya
25
Java
Scala
Python
Updated on 06-Jul-2020 06:24:19