How to create a json_template? - java

I'm creating some code and I saw an example here on this forum, and I have a hard time using geojson.
Whenever it is giving an error in raw because I did not add this json_template
private String getGeoString() throws IOException{
InputStream is = getResources().openRawResource(R.raw.json_template);
Writer writer = new StringWriter();
char[] buffer = new char [1024];
try{
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n= reader.read(buffer)) != -1){
writer.write(buffer, 0, n);
}
}finally {
is.close();
}
String jsonString = writer.toString();
return jsonString();
}
How can I solve this error?

If you would like to create a json file in your app, you can first create a json_template.json file in your app -> res -> raw folder.
In that file, you can put the entire json response received upon querying.
A useful tool to see the json traversal in the nested response is JSON Pretty Print.
Then you can try:
public static String getGeoString(Context context) throws IOException {
InputStream is = context.getResources().openRawResource(R.raw.json_template);
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
// The local variable 'jsonString' can be inlined as below
return writer.toString();
}
It should work. Hope this is helpful.

Related

image not showing when transferred using InputStream and OutputStream in java

This is my test program. I need it to apply somewhere.This may be small, sorry for that. But I'm a starter still. So kindly help me.
try{
File file1 = new File("c:\\Users\\prasad\\Desktop\\bugatti.jpg");
File file2 = new File("c:\\Users\\prasad\\Desktop\\hello.jpg");
file2.createNewFile();
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file1)));
String data = null;
StringBuilder imageBuild = new StringBuilder();
while((data = reader.readLine())!=null){
imageBuild.append(data);
}
reader.close();
BufferedWriter writer = new BufferedWriter(new PrintWriter(new FileOutputStream(file2)));
writer.write(imageBuild.toString());
writer.close();
}catch(IOException e){
e.printStackTrace();
}
This is file1
and This is file2
You can do either of these two:
private static void copyFile(File source, File dest) throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
or maybe this if you want to use streams:
private static void copyFile(File source, File dest)
throws IOException {
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream(source);
output = new FileOutputStream(dest);
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf)) > 0) {
output.write(buf, 0, bytesRead);
}
} finally {
input.close();
output.close();
}
}
Images do not contain lines or even characters. You therefore should not be using readLine() or even Readers or Writers. You should rewrite the copy loop using input and output streams directly.

BufferedReader.readline() returning null value

I am creating this method which takes an InputStream as parameter, but the readLine() function is returning null. While debugging, inputstream is not empty.
else if (requestedMessage instanceof BytesMessage) {
BytesMessage bytesMessage = (BytesMessage) requestedMessage;
byte[] sourceBytes = new byte[(int) bytesMessage.getBodyLength()];
bytesMessage.readBytes(sourceBytes);
String strFileContent = new String(sourceBytes);
ByteArrayInputStream byteInputStream = new ByteArrayInputStream(sourceBytes);
InputStream inputStrm = (InputStream) byteInputStream;
processMessage(inputStrm, requestedMessage);
}
public void processMessage(InputStream inputStrm, javax.jms.Message requestedMessage) {
String externalmessage = tradeEntryTrsMessageHandler.convertInputStringToString(inputStrm);
}
public String convertInputStringToString(InputStream inputStream) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
return sb.toString();
}
Kindly try this,
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
i believe that raw data as it is taken is not formatted to follow a character set. so by mentioning UTF-8 (U from Universal Character Set + Transformation Format—8-bit might help
Are you sure you are initializing and passing a valid InputStream to the function?
Also, just FYI maybe you were trying to name your function convertInputStreamToString instead of convertInputStringToString?
Here are two other ways of converting your InputStream to String, try these maybe?
1.
String theString = IOUtils.toString(inputStream, encoding);
2.
public String convertInputStringToString(InputStream is) {
java.util.Scanner s = new java.util.Scanner(is, encoding).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
EDIT:
You needn't explicitly convert ByteArrayInputStream to InputStream. You could do directly:
InputStream inputStrm = new ByteArrayInputStream(sourceBytes);

Java fast stream copy with ISO-8859-1

I have the following code, which will read in files in ISO-8859-1, as thats what is required in this application,
private static String readFile(String filename) throws IOException {
String lineSep = System.getProperty("line.separator");
File f = new File(filename);
StringBuffer sb = new StringBuffer();
if (f.exists()) {
BufferedReader br =
new BufferedReader(
new InputStreamReader(
new FileInputStream(filename), "ISO-8859-1"));
String nextLine = "";
while ((nextLine = br.readLine()) != null) {
sb.append(nextLine+ " ");
// note: BufferedReader strips the EOL character.
// sb.append(lineSep);
}
br.close();
}
return sb.toString();
}
The problem is it is pretty slow. I have this function, which is MUCH faster, but I can not seem to find how to place the character encoding:
private static String fastStreamCopy(String filename)
{
String s = "";
FileChannel fc = null;
try
{
fc = new FileInputStream(filename).getChannel();
MappedByteBuffer byteBuffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
int size = byteBuffer.capacity();
if (size > 0)
{
byteBuffer.clear();
byte[] bytes = new byte[size];
byteBuffer.get(bytes, 0, bytes.length);
s = new String(bytes);
}
fc.close();
}
catch (FileNotFoundException fnfx)
{
System.out.println("File not found: " + fnfx);
}
catch (IOException iox)
{
System.out.println("I/O problems: " + iox);
}
finally
{
if (fc != null)
{
try
{
fc.close();
}
catch (IOException ignore)
{
}
}
}
return s;
}
Any one have an idea of where i should be putting the ISO encoding?
From the code you posted, you're not trying to "copy" the stream, but read it into a string.
You can simply provide the encoding in the String constructor:
s = new String(bytes, "ISO-88591-1");
Personally I'd just replace the whole method with a call to the Guava method Files.toString():
String content = Files.toString(new File(filename), StandardCharsets.ISO_8859_1);
If you're using Java 6 or earlier, you'll need to use the Guava field Charsets.ISO_8859_1 instead of StandardCharsets.ISO_8859_1 (which was only introduced in Java 7).
However your use of the term "copy" suggests that you want to write the result to some other file (or stream). If that is true, then you don't need to care about the encoding at all, since you can just handle the byte[] directly and avoid the (unnecessary) conversion to and from String.
where you are converting bytes to string e.g. s = new String(bytes, encoding); or vice versa.

Not able to process big file inside a zip file using ZipInputStream

I am having a below mentioned java class which extracts a zip, and one by one convert its content to string and print to console.
Problem is, when the file present inside the zip is big ~80KB. Entire content is not getting displayed (only 3/4 of the data is getting converted to string and displayed in console).
Secondly below mentioned code is introducing null/space in between and also if the file size is small ~1KB
what is wrong in below mentioned code.
public static void main(String[] args) throws Exception {
byte[] buf = new byte[1024];
final int BUFFER = 1024;
String fName = "c:\\DOC00001.zip";
ZipInputStream zinstream = new ZipInputStream(
new FileInputStream(fName));
ZipEntry zentry = zinstream.getNextEntry();
while (zentry != null) {
byte data[] = new byte[BUFFER];
ByteArrayOutputStream out = new ByteArrayOutputStream();
while ((zinstream.read(data, 0, BUFFER)) != -1) {
out.write(data);
}
InputStream is = new ByteArrayInputStream(out.toByteArray());
StringWriter writer = new StringWriter();
IOUtils.copy(is, writer, "UTF-8");
String response = writer.toString();
System.out.println(response);
zentry = zinstream.getNextEntry();
}
zinstream.close();
}
The read method is not guaranteed to read a full buffer; the number of bytes that have been read is returned. The correct way to extract data from a zip file, or any InputStream in general, would be:
byte[] data = new byte[BUFFER];
ByteArrayOutputStream out = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = zinstream.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, bytesRead);
}
Or, since you are already using IOUtils,
ByteArrayOutputStream out = new ByteArrayOutputStream();
IOUtils.copy(zinstream, out);
Or, given that you write to a ByteArrayOutputStream only to later write to a String, you can skip the ByteArrayOutputStream entirely:
while (zentry != null) {
StringWriter writer = new StringWriter();
IOUtils.copy(zinstream, writer, "UTF-8");
String response = writer.toString();
System.out.println(response);
zentry = zinstream.getNextEntry();
}

Android App Internal Data Storage

I am attempting to save an array of longs as a text file using the Android's internal memory, and then access that array in a different activity. After noticing that was broken, I isolated the problem in this chunk of code below.
long[] timings = {200, 400, 600, 1400};
try {
FileOutputStream fos = openFileOutput("timings", Context.MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.write(Arrays.toString(timings));
osw.close();
FileInputStream fis = openFileInput("timings");
InputStreamReader isReader = new InputStreamReader(fis);
char[] buffer = new char[timings.length];
isReader.read(buffer);
textField.setText(Arrays.toString(buffer));
fis.close();
} catch (IOException e1) {
e1.printStackTrace();
}
The text field that is set to display what is read from the file has the following result:
[[,2,0,0]
The result I expected was the original array from above. What am I doing wrong here? Any help or advice would be appreciated.
Replace this :
InputStreamReader isReader = new InputStreamReader(fis);
char[] buffer = new char[timings.length];
isReader.read(buffer);
textField.setText(Arrays.toString(buffer));
with this :
DataInputStream in = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String sTemp1 = "", sTemp2 = "";
while ((sTemp1 = br.readLine()) != null) {
sTemp2 = sTemp1;
}
in.close();
textField.setText(sTemp2);
I hope it will help you.

Categories

Resources