Android App Internal Data Storage - java

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.

Related

How to create a json_template?

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.

Java Download mp4 from url

I try to download a mp4 file from my Server and save it as a mp4 file. A file is created and has a size of 25 MB, but i can't play it with a video player.
Here is my code:
HttpURLConnection con = (HttpURLConnection) new URL(serveradress).openConnection();
con.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; "
+ "Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like
Gecko)"
+ " Chrome/53.0.2785.143 Safari/537.36");
InputStream is = con.getInputStream();
System.out.println(con.getResponseCode());
String line = null;
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
while((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
is.close();
String outVideo = stringBuilder.toString();
File file = new File("C:\\Benutzer\\Admin\\Desktop\\video.mp4");
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);
writer.write(outVideo);
writer.close();
} catch(Exception ex) {
ex.printStacktrace();
}
Any help is really appreciated.
I am guessing the reason you cant play a saved video is that you are saving a string instead of byte[] data of the video.
Try using instead BufferedInputStream to read bytes
And use FileOutputStream to save those bytes to the file
Dont use StringBuilder
Thanks a lot #A.Bergen with your tip i have found a solution and now it works.
File file = new File("C:\\Benutzer\\Admin\\Desktop\\youtube.mp4");
file.getParentFile().mkdirs();
BufferedInputStream bufferedInputStream = new BufferedInputStream(new URL(decodedDownloadLink).openStream());
FileOutputStream fileOutputStream = new FileOutputStream("C:/Benutzer/Admin/Desktop/youtube.mp4");
int count=0;
byte[] b = new byte[100];
while((count = bufferedInputStream.read(b)) != -1) {
fileOutputStream.write(b, 0,count);
}

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.

String to byte convertion in java

i m new in java....i m trying to read a text file using file input stream. i m reading text line by line and set as a string.. now i want to convert string into byte. but i m getting a number format exception.. please help me to solve this problem.
FileInputStream fstream = new FileInputStream("C:/Users/data.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
byte[] bytes = null;
String str;
int i=0;
while ((str = br.readLine()) != null)
{
bytes[i] = Byte.parseByte(str,16);
i++;
}
in.close();
Try
byte[] bytes = str.getBytes();
instead of
bytes[i] = Byte.parseByte(str,16);
Also I recommend to specify encoding for InputStreamReader:
BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
Keep in mind that Java String length and internal representation would not be same to C.
You can simply use the getBytes() method from the String class :
str.getBytes()
Or if you don't use the default character set :
str.getBytes(myCharSet);
you can use,
str.getBytes() which will convert the string into the byte array.
you can try this code.
fstream = new FileInputStream("C:/Users/s.hussain/Desktop/test3.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
byte[] bytes = null;
String str;
int i=0;
while ((str = br.readLine()) != null)
{
bytes = str.getBytes();
i++;
System.out.println(bytes.length);
}
in.close();

Socket Programming file upload issues?Complete file not uploading

Hi i am using the following code for uploding my file from android phone to the server bt the file does not upload completely..e.g i uploded a 11kb file and got only 8kb file at the server.What am i doing wrong?
Client side
Socket skt = new Socket"112.***.*.**", 3000);
String FileName=fil.getName();
PrintWriter out2 = new PrintWriter(new BufferedWriter(new OutputStreamWriter(skt.getOutputStream())),true);
out2.println("Upload");
out2.println(FileName);
out2.println(spinindx);
out2.println(singleton.arrylst_setngs.get(0).toString());
out2.println(singleton.arrylst_setngs.get(1).toString());
out2.println(singleton.arrylst_setngs.get(2).toString());
out2.println(singleton.arrylst_setngs.get(3).toString());
out2.println(singleton.arrylst_setngs.get(4).toString());
out2.flush();
//Create a file input stream and a buffered input stream.
FileInputStream fis = new FileInputStream(fil);
BufferedInputStream in = new BufferedInputStream(fis);
BufferedOutputStream out = new BufferedOutputStream(skt.getOutputStream());
//Write the file to the server socket
int i;
byte[] buf = new byte[512];
while ((i = in.read(buf)) != -1) {
out.write(buf,0,i);
publishProgress(in.available());
System.out.println(i);
}
//Close the writers,readers and the socket.
in.close();
out.flush();
out.close();
out2.close();
skt.close();
}
catch( Exception e ) {
System.out.println(e);
}
The server side
InputStream inStream = socket.getInputStream();
BufferedReader inm = new BufferedReader(new InputStreamReader(inStream));
String Request=inm.readLine();
if(Request.equals("Upload")){
fileName = inm.readLine();
chosn = inm.readLine();
lt=inm.readLine();
cs = inm.readLine();
om = inm.readLine();
o = inm.readLine();
check=inm.readLine();
//Read, and write the file to the socket
BufferedInputStream in = new BufferedInputStream(inStream);
int i=0;
File f=new File("D:/data/"+filePrefx+fileName);
if(!f.exists()){
f.createNewFile();
}
FileOutputStream fos = new FileOutputStream("D:/data/"+filePrefx+fileName);
BufferedOutputStream out = new BufferedOutputStream(fos);
byte[] buf = new byte[512];
while ((i = in.read(buf)) != -1) {
System.out.println(i);
out.write(buf,0,i);
System.out.println("Receiving data...");
}
in.close();
inStream.close();
out.close();
fos.close();
socket.close();
Looks like you are using both a BufferedReader and a BufferedInputStream on the same underlying socket at the server side, and two kinds of output stream/writer at the client. So your BufferedReader is buffering, which is what it's supposed to do, and thus 'stealing' some of the data you're expecting to read with the BufferedInputStream. Moral: you can't do that. Use DataInputStream & DataOutputStream only, and writeUTF()/readUTF() for the 8 lines you are reading from the client before the file.
You shared the same underlying InputStream between your BufferedReader and bufferedInputStream.
What happened is, when you do the reading through BufferedReader, it reads more than the a few lines you requested from the underlying InputStream into its own internal buffer. And when you create the BufferedInputStream, the data has already been read by the BufferedReader. So Apart from what EJP suggested not to use any buffered class, you can create the BufferedInputStream, and then create the Reader on Top of it. The code is something like this:
BufferedInputStream in = new BufferedInputStream(inStream);
Reader inm = new InputStreamReader(in);
Add it to the beginning of your server code and remove this line:
BufferedInputStream in = new BufferedInputStream(inStream);
See this, i never tried though
void read() throws IOException {
log("Reading from file.");
StringBuilder text = new StringBuilder();
String NL = System.getProperty("line.separator");
Scanner scanner = new Scanner(new FileInputStream(fFileName), fEncoding);
try {
while (scanner.hasNextLine()){
text.append(scanner.nextLine() + NL);
}
}
finally{
scanner.close();
}
log("Text read in: " + text);
}
Shamelessly copied from
http://www.javapractices.com/topic/TopicAction.do?Id=42

Categories

Resources