I am attempting to read a text file and create a JSONObject in an Android application, but after reading the text file into a string, I get a JSONException thrown when I try to construct a JSONObject using the string.
Here is the code I am using:
InputStream is = this.getResources().openRawResource(R.raw.quiz);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String jsString = "";
String line = null;
while((line = reader.readLine()) != null){
jsString += line;
}
is.close();
reader.close();
try {
return new JSONObject(jsString);
} catch (JSONException e) {
}
return null;
Here is the text file I am reading from, quiz.txt:
{"length":3,"questions":[{"questionText":"Is mayonaise an instrument?","answers":["Yes","no","no","no","no"],"correctAnswer":0},{"questionText":"10^2","answers":["1","10","100","1000","over 9000"],"correctAnswer":1},{"questionText":"Dogs Name?","answers":["Barky","Steve","Rex","Daisy","Wormy"],"correctAnswer":3}]}
Try using this method to read the file contents into a string.
public static String getJsonFromResource( int resource, Context context ) {
InputStream inputStream = context.getResources().openRawResource( resource );
BufferedReader r = new BufferedReader( new InputStreamReader( inputStream ) );
StringBuilder stringBuilder = new StringBuilder();
String line;
String jsonString = null;
try {
while (( line = r.readLine() ) != null) {
stringBuilder.append( line );
}
jsonString = stringBuilder.toString();
}
catch (Exception e) {
Log.e( "GetJsonFromResource", Log.getStackTraceString( e ) );
}
return jsonString;
}
Related
This prints everything one one line. My original text file has different lines. How to still get the content line by line after the file is zipped? I am working on Mac.
public static void main(String[] args) throws IOException {
QuickTest mfe = new QuickTest();
ZipFile zip = new ZipFile("test.txt.zip");
for (Enumeration e = zip.entries(); e.hasMoreElements(); ) {
ZipEntry entry = (ZipEntry) e.nextElement();
System.out.println(entry.getName());
if (!entry.isDirectory()) {
if (FilenameUtils.getExtension(entry.getName()).equals("txt")) {
StringBuilder out = getTxtFiles(zip.getInputStream(entry));
System.out.println(out.toString());
}
}
}
System.out.println("Done");
}
private static StringBuilder getTxtFiles(InputStream in) {
StringBuilder out = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
try {
while ((line = reader.readLine()) != null) {
out.append(line);
}
} catch (IOException e) {
// do something, probably not a text file
e.printStackTrace();
}
return out;
}
Inside your method:
private static StringBuilder getTxtFiles(InputStream in) {
StringBuilder out = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
The following loop:
try {
while ((line = reader.readLine()) != null) {
out.append(line);
}
reads lines but the Java readLine() method does not append an end-of-line character. You'll need to add a newline (or carriage return for the Mac) to see lines.
try {
while ((line = reader.readLine()) != null) {
out.append(line);
out.append( '\n' );
}
The code below only brings up the first line of code and stops. I would like to return each line of code until there are no more.
private String GetPhoneAddress() {
File directory = Environment.getExternalStorageDirectory();
File myFile = new File(directory, "mythoughtlog.txt");
//File file = new File(Environment.getExternalStorageDirectory() + "mythoughtlog.txt");
if (!myFile.exists()){
String line = "Need to add smth";
return line;
}
String line = null;
//Read text from file
//StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(myFile));
line = br.readLine();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
return line;
}
You could loop over the results of readLine() and accumulate them until you get a null, indicating the end of the file (BTW, note that your snippet neglected to close the reader. A try-with-resource structure could handle that):
try (BufferedReader br = new BufferedReader(new FileReader(myFile))) {
String line = br.readLine();
if (line == null) {
return null;
}
StringBuilder retVal = new StringBuilder(line);
line = br.readLine();
while (line != null) {
retVal.append(System.lineSeparator()).append(line);
line = br.readLine();
}
return retVal.toString();
}
if you're using Java 8, you can save a lot of this boiler-plated code with the newly introduced lines() method:
try (BufferedReader br = new BufferedReader(new FileReader(myFile))) {
return br.lines().collect(Collectors.joining(System.lineSeparator()));
}
A considerably less verbose solution:
try (BufferedReader br = new BufferedReader(new FileReader(myFile))) {
StringBuilder retVal = new StringBuilder();
while ((line = br.readLine()) != null) {
retVal.append(line).append(System.lineSeparator());
}
return retVal.toString();
}
I'm trying to read data from a text file and create Item Objects with it.
Item Objects have fields String title, String formatt, boolean onLoan, String loanedTo and String dateLoaned. In my save()method, I print every object to a text file in a new line and the fields are seperated by "$" (dollar sign). How can I read the text file line by line and create a new object from each line and add it to an array.
TextFile Example:
StarWars$DVD$false$null$null
Aliens$Bluray$true$John$Monday
public void save() {
String[] array2 = listForSave();
PrintWriter printer = null;
try {
printer = new PrintWriter(file);
for (String o : array2) {
printer.println(o);
}
printer.close();
} catch ( IOException e ) {
e.printStackTrace();
}
}
public void open(){
try{
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println("Contents of file:");
System.out.println(stringBuffer.toString());
}catch ( IOException e ) {
e.printStackTrace();
}
}
Thanks everyone. Here's my final code:
public void open(){
try{
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
String[] strings;
while ((line = bufferedReader.readLine()) != null) {
strings = line.split("\\$");
String title = strings[0];
String format = strings[1];
boolean onLoan = Boolean.parseBoolean(strings[2]);
String loanedTo = strings[3];
String dateLoaned = strings[4];
MediaItem superItem = new MediaItem(title,format, onLoan,loanedTo,dateLoaned);
items.add(superItem);
}
fileReader.close();
}catch ( IOException e ) {
e.printStackTrace();
}
}
String line = // input line e.g. "Aliens$Bluray$true$John$Monday"
String[] strings = line.split("\\$"); // use regex matching "$" to split
String title = strings[0];
String formatt = strings[1];
boolean onLoan = Boolean.parseBoolean(strings[2]);
String loanedTo = strings[3];
String dateLoaned = strings[4];
// TODO: create object from those values
Maybe you need to handle null differently (in case you want the String "null" to be converted to null); note that you can't distinguish if null or "null" was saved.
This function converts "null" to null and returns the same string otherwise:
String convert(String s) {
return s.equals("null") ? null : s;
}
Reading the objects to an array
Since you don't know the number of elements before reading all lines, you have to work around that:
Write the number of objects in the file as first line, which would allow you to create the array before reading the first object. (Use Integer.parseInt(String) to convert the first line to int):
public void save() {
String[] array2 = listForSave();
PrintWriter printer = null;
try {
printer = new PrintWriter(file);
printer.println(array2.length);
for (String o : array2) {
printer.println(o);
}
printer.close();
} catch ( IOException e ) {
e.printStackTrace();
}
}
public void open(){
try{
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
int arraySize = Integer.parseInt(stringBuffer.readLine());
Object[] array = new Object[arraySize];
int index = 0;
String line;
while ((line = bufferedReader.readLine()) != null) {
// split line and create Object (see above)
Object o = // ...
array[index++] = o;
}
//...
}catch ( IOException e ) {
e.printStackTrace();
}
//...
}
or
Use a Collection, e.g. ArrayList to store the objects and use List.toArray(T[]) to get an array.
quick and dirty solution might be...
public void open(){
try{
ArrayList<Item> list = new ArrayList<Item>(); //Array of your ItemObject
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
Item itm = new Item(); //New Item Object
String [] splitLine = line.split("\\$");
item.title = splitLine[0];
item.format = splitLine[1];
item.onLoan = Boolean.parseBoolean(splitLine[2]);
item.loanedTo = splitLine[3];
item.dateLoaned = splitLine[4];
list.add(itm);
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println("Contents of file:");
System.out.println(stringBuffer.toString());
}catch ( IOException e ) {
e.printStackTrace();
}
}
But this is won't scale if you need to re-arrange or add new fields.
You could try this to "parse" every line of your file
String[] result = "StarWars$DVD$false$null$null".split("\\$");
for (int i=0; i<result.length; i++) {
String field = result[i]
... put the strings in your object ...
}
hi i want to read large remote file into string using buffered reader.but i got half data of remote file.
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputstream),8*1024);
StringBuilder sb = new StringBuilder(999999);
String line;
while ((line = reader.readLine()) != null) {
Log.e("Line is ",line);
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("Content: ", sb.toString());
How to get full data of remote file?
It seems there is nothing wrong with your code but you can try it this way:
private String ReceiveData(InputStream inputstream){
StringBuilder sb = null;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader( inputstream),8*1024);
sb = new StringBuilder();
String str;
int numRead = 0;
try {
if (bufferedReader!=null) {
if (bufferedReader.ready()) {
try {
while ((numRead = bufferedReader.read()) >= 0) {
//convert asci to char and then to string
str = String.valueOf((char) numRead);
if ((str != null)&& (str.toString() != "")) {
sb.append(str);
}
if (!bufferedReader.ready()){
//no more characters to read
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
//loop exited, check for null
if (sb != null) {
return sb.toString();
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return "";
}
Hope I helped.
here string data values comes from shell script code.i need to show this resultant values in json format
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(new String[]{"/home/admin/institutestatus.sh"});
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
while ((line = input.readLine()) != null) {
Gson gson =new Gson();
System.out.println(gson.toJson(line));
}
} catch (Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
JSONArray arr = new JSONArray();
while ((line = input.readLine()) != null) {
JSONObject obj = new JSONObject();
obj.put("value",line);
arr.add(obj);
}
I've used this function to convert InputStream to String and the to JSONObject.
public static String load(final InputStream in) {
String data = "";
try {
InputStreamReader is = new InputStreamReader(in, Charset.forName("UTF-8"));
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(is);
String read = br.readLine();
while (read != null) {
sb.append(read);
read = br.readLine();
}
data = sb.toString();
} catch (IOException e) {
System.out.println(e.getMessage());
}
return data;
}
You use the GSON in order to don't have to work with the Strings in the first place...