Android save and read files - android

I'm trying to write and then read file:
private void writeToFile(String data,String filename) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(this.openFileOutput(filename, Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
} catch (IOException e) {
//Log.e("Exception", "File write failed: " + e.toString());
serviceNotifer("FILE WRITE", "ERROR", 687);
}
}
writeToFile("SOMETEXT!", "input.bin");
/* try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}*/
File file = new File("input.bin");
FileInputStream fis = null;
try {
serviceNotifer("WriteFile", "Stop2", 922);
fis = new FileInputStream(file);
int bytesRead=0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
while ((bytesRead = fis.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byte[] bytes = bos.toByteArray();
char[] hexArray = "0123456789ABCDEF".toCharArray();
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
UpdateFileString=fis.toString();
serviceNotifer("FILE C:", UpdateFileString, 922);
int ByteNum=UpdateFileString.length();
SentNewIndexVal(0xE001,ByteNum);
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.toString());
serviceNotifer("FILE", "ERROR1"+ e.toString(), 687);
} catch (IOException e) {
System.out.println("Exception reading file: " + e.toString());
serviceNotifer("FILE", "ERROR2", 687);
} finally {
try {
if (fis != null) fis.close();
} catch (IOException ignored) {
}
}
After recording, the application becomes larger than 15 kilobytes. But I get oshmbku "ERROR1" - File not found. Where is my mistake? I think it's related with file path...

Related

Recieving File with Socket in Android

I want to transfer a file between server and client, Server is a Windows program written in Delphi with Indy and Client is an Android
this is my client code for reading from socket :
...
InputStream IS = S.getInputStream();
byte[] FBytes = new byte[FileSize];
FileOutputStream FOS = new FileOutputStream(TempFile);
BufferedOutputStream BOS = new BufferedOutputStream(FOS);
int BytesRead = IS.read(FBytes);
int CurrProgress = BytesRead;
do {
Log.d("DOWNLOAD", "BytesRead2 = " + Integer.toString(BytesRead));
if(CurrProgress < FBytes.length) {
Log.d("DOWNLOAD", "prog < BytesRead" );
BytesRead = IS.read(FBytes);
if (BytesRead > 0)
CurrProgress += BytesRead;
B.clear();
B.putInt("ProgValue", CurrProgress);
Msg.what = MSG_FILE_PROGRESS;
Hdlr.dispatchMessage(Msg);
Log.d("DOWNLOAD", "BytesRead = " + Integer.toString(BytesRead));
}
} while (BytesRead > 0);
Log.d(TAG, "Download Loop Finished");
File will download but the problem is size of downloaded file is lower than original file and the socket read command stay on last read. in other words file has been downloaded but CurrProgress is lower than FBytes.length so while loop execute onetime more and program hangs on read command because there is no more data sent from server
I have been tested server with an windows program and there is no problem in the server code
I have tested many ways like this but no chance :
int BytesRead = IS.read(FBytes, 0, FBytes.length);
int CurrProgress = BytesRead;
do {
Log.d("DOWNLOAD", "BytesRead2 = " + Integer.toString(BytesRead));
if(CurrProgress < FBytes.length) {
Log.d("DOWNLOAD", "prog < BytesRead" );
BytesRead = IS.read(FBytes, CurrProgress, (FBytes.length - CurrProgress));
...
FileSize value is correct and came from server as a string value before reading file bytes
What goes wrong ?!, thanks ...
Edit :
Complete code do many other jobs but code of reading file is like this :
public void Run()
{
Running = true;
try{
try{
InetAddress ServerAddr = InetAddress.getByName(SERVER_IP);
S = new Socket(ServerAddr, SERVER_PORT);
Log.d(TAG, "Connecting ...");
Out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(S.getOutputStream())), true);
In = new BufferedReader(new InputStreamReader(S.getInputStream()));
switch (Job) {
...
}
case GetFile: {
this.SendMessage(Cmd);
response = In.readLine();
if(response.equals("1"))
{
Hdlr.sendEmptyMessage(MSG_SERVER_ACCEPT);
response = In.readLine();
int FileSize = Integer.parseInt(response);
if (context.getFilesDir().getFreeSpace() < 3 * FileSize)
{
Hdlr.sendEmptyMessage(MSG_ERROR_FREESPACE);
Log.d(TAG, "There is no Free Space !");
}
else {
final Message Msg = new Message();
final Bundle B = new Bundle();
B.putInt("FSize", FileSize);
Msg.what = MSG_FILE_SIZE;
Msg.setData(B);
Hdlr.dispatchMessage(Msg);
try {
File TempDir, TempFile, MainDir, MainFile;
switch(FileType)
{
case 2 :
TempDir = new File(context.getCacheDir(), "TempMP3");
if(!TempDir.exists()) {
TempDir.mkdir();
}
TempFile = new File(TempDir, Integer.toString(FileIndex) + ".mp3");
if(TempFile.exists()) {
TempFile.delete();
}
break;
default :
TempDir = new File(context.getCacheDir(), "TempLevel");
if(!TempDir.exists()) {
TempDir.mkdir();
}
TempFile = new File(TempDir, Integer.toString(FileIndex) + ".zip");
if(TempFile.exists()) {
TempFile.delete();
}
}
InputStream IS = S.getInputStream();
byte[] FBytes = new byte[4096];
FileOutputStream FOS = new FileOutputStream(TempFile);
BufferedOutputStream BOS = new BufferedOutputStream(FOS);
int BytesRead = 0;
int CurrProgress = 0;
do {
Log.d("DOWNLOAD", "prog < BytesRead" );
BytesRead = IS.read(FBytes, 0, FBytes.length);
BOS.write(FBytes, 0, BytesRead);
if (BytesRead > 0)
CurrProgress += BytesRead;
B.clear();
B.putInt("ProgValue", CurrProgress);
Msg.what = MSG_FILE_PROGRESS;
Hdlr.dispatchMessage(Msg);
Log.d("DOWNLOAD", "BytesRead = " + Integer.toString(BytesRead));
} while (CurrProgress < FileSize);
Log.d(TAG, "Download Loop Finished");
if (CurrProgress != FBytes.length) {
BOS.close();
Hdlr.sendEmptyMessage(MSG_ERROR_FILESIZE);
Log.d(TAG, "File Size Problem");
} else {
BOS.close();
Log.d(TAG, "File Downloaded successfully, Preparing to Unzip ... ");
try {
MainDir = new File(context.getFilesDir(), "Levels");
if(!MainDir.exists())
{
MainDir.mkdir();
}
File LevelDir = new File(MainDir, Integer.toString(FileIndex));
if(!LevelDir.exists())
{
LevelDir.mkdir();
}
else
{
LevelDir.delete();
}
FileInputStream fin = new FileInputStream(TempFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
MainFile = new File(LevelDir, ze.getName());
FileOutputStream FOut = new FileOutputStream(MainFile);
for (int c = zin.read(); c != -1; c = zin.read()) {
FOut.write(c);
}
zin.closeEntry();
FOut.close();
}
zin.close();
} catch (Exception e) {
Log.d(TAG, "Unzip Error : ", e);
}
}
} catch (Exception E) {
Err = 1;
Log.d(TAG, "Get File Error : ", E);
}
}
}
else
{
if (Listener != null)
{
Listener.callbackMessageReceiver(response);
Hdlr.sendEmptyMessage(MSG_ERROR_SERVER);
}
}
break;
}
...
}
}catch (Exception e)
{
Hdlr.sendEmptyMessage(MSG_ERROR_SEND);
Log.d(TAG, "Connect Error : ", e);
}
finally{
if(Out != null) {
Out.flush();
Out.close();
}
if(In != null)
{
In.close();
}
S.close();
Log.d(TAG, "Err Value is : " + Integer.toString(Err));
if(Err == 0)
{
Hdlr.sendEmptyMessage(MSG_SUCCESS);
}
Log.d(TAG, "Sending Ends");
}
}catch (Exception E){
Log.d(TAG, "Error : ", E);
}
}
CurrProgress is lower than FileSize ( the difference is about 4 or 5 KB ) and the while loop hangs on read command !
Problem solved, I will post it as answer, it may be useful
The problem was that server sends File immediately after sending FileSize and I think the BufferedReader gets some bytes of File so the size of bytes given by IS are lower than FileSize, example of Server :
...
WriteLn(FileSize);
Write(FileStream);
...
Now, Server first sends FileSize then wait for a response from client, after checking freespace in client it sends a Ready response to server and then Server sends the File Stream, for example :
...
WriteLn(FileSize);
Response := ReadLn();
if Response = "READY" then
Write(FileStream);
...
and codes in client are like this :
...
BufferedInputStream BIS = new BufferedInputStream(S.getInputStream());
In = new BufferedReader(new InputStreamReader(S.getInputStream()));
...
response = In.readLine();
int FileSize = Integer.parseInt(response);
if (context.getFilesDir().getFreeSpace() < 3 * FileSize)
{
Hdlr.sendEmptyMessage(MSG_ERROR_FREESPACE);
Log.d(TAG, "There is no Free Space !");
this.SendMessage("NOT_READY");
}
else {
...
try {
this.SendMessage("READY");
byte[] FBytes = new byte[8192];
FileOutputStream FOS = new FileOutputStream(TempFile);
BufferedOutputStream BOS = new BufferedOutputStream(FOS);
int BytesRead = 0;
int CurrProgress = 0;
while (CurrProgress < FileSize){
Log.d("DOWNLOAD", "Available : " + Integer.toString(BIS.availabl
BytesRead = BIS.read(FBytes, 0, FBytes.length);
BOS.write(FBytes, 0, BytesRead);
if (BytesRead > 0)
CurrProgress += BytesRead;
B.clear();
B.putInt("ProgValue", CurrProgress);
Msg.what = MSG_FILE_PROGRESS;
Hdlr.dispatchMessage(Msg);
Log.d("DOWNLOAD", "BytesRead = " + Integer.toString(BytesRead));
}
There is no problem and everything works fine

Sending picture in Android (Socket Programming)

I'm trying to receive a Picture on my Android phone from Server using socket programming.I use this code but in.read() in 4th line always returns -1.
How can I fix this problem?
Client Code:
try {
x = new byte[picLength2];
int current = 0;
int byteRead = in.read(x, 0, x.length);
current = byteRead;
do {
byteRead = in.read(x, current, (x.length - current));
if (byteRead >0) {
current += byteRead;
}
} while (byteRead > -1);
}catch (IOException e){
e.printStackTrace();
}
Server Code:
try {
File myFile = new File("C:/onlinegame/null.jpg");
mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.write(mybytearray);
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}

DataInputStream read(byte[] buffer) is returned irrelevant data

How to receive original content and file name from server side code.
Client Code
public void send1(Socket socket)
{
try
{
dataOutputStream = new DataOutputStream(socket.getOutputStream());
File file = new File(Environment.getExternalStorageDirectory().toString() + "/" + "temp.txt");
FileInputStream fis = new FileInputStream(file);
//write file length
dataOutputStream.writeLong(file.length());
Log.i("File Size", "" + file.length());
//write file names
dataOutputStream.writeUTF(file.getName());
Log.i("File Name", "" + file.getName());
//write file to dos
byte[] buf = new byte[4092];
int n = 0;
while((n = fis.read(buf)) != -1)
{
Log.i("length bytes", "" + n);
dataOutputStream.write(buf, 0, n);
}
dataOutputStream.flush();
dataOutputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
File Name as temp.txt and Content as Hello
Server Code
public void receive1(Socket socket)
{
try
{
inputStream = socket.getInputStream();
dataInputStream = new DataInputStream(inputStream);
File file = new File(Environment.getExternalStorageDirectory().toString() + "/" + "test.txt");
FileOutputStream fos = new FileOutputStream(file);
int n = 0;
byte[] buf = new byte[4092];
//read file name
/*String fileName = "";
try
{
fileName = dataInputStream.readUTF();
}
catch (Exception e)
{
e.printStackTrace();
}
Log.i("File Name", "" + fileName);*/
//read file size
long fileSize = 0;
try
{
fileSize = dataInputStream.readLong();
}
catch (Exception e)
{
e.printStackTrace();
}
Log.i("File Size", "" + fileSize);
//read file
while((n = dataInputStream.read(buf)) != -1)
{
Log.i("length bytes", "" + n);
fos.write(buf, 0, n);
}
fos.flush();
fos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
File Name as test.txt and Content as temp.txtHello.
In this test.txt file, contains temp.txt. I am not getting file name from dataInputStream.readUTF().
Where I mistaken code...
If I called readUTF() method, then I am getting the Exception
Exception as
java.io.EOFException
at libcore.io.Streams.readFully(Streams.java:83)
at java.io.DataInputStream.readFully(DataInputStream.java:99)
at java.io.DataInputStream.decodeUTF(DataInputStream.java:178)
at java.io.DataInputStream.decodeUTF(DataInputStream.java:173)
at java.io.DataInputStream.readUTF(DataInputStream.java:169)
You wrote the Long before the String in the inputStream of the send method. What you did in the server code is that you are expecting to recieve String before the Long which in reserved on what you did in your send method.
solution:
switch reading long first then string
sample:
//read file size
long fileSize = 0;
try
{
fileSize = dataInputStream.readLong();
}
catch (Exception e)
{
e.printStackTrace();
}
Log.i("File Size", "" + fileSize);
//read file name
String fileName = "";
try
{
fileName = dataInputStream.readUTF();
}
catch (Exception e)
{
e.printStackTrace();
}
Log.i("File Name", "" + fileName);

android app connecting to google drive and downloading a file to sd card

My android app connects to google drive and checks for a file on the drive, if the file isn't present then it downloads it to sdcard. the following code does the downloading .
the problem that occurs is that the file which gets downloaded is showing 0 bytes after downloading. please help me locate the error in the code. thanks for helping out .
private void savefile(String filename, InputStream in , Boolean replace ) {
try {
java.io.File f = new java.io.File(filename);
logonscreen("trying to savefile :"+filename);
if(replace) {
showToast("replace:"+replace.toString());
OutputStream stream = new BufferedOutputStream(new FileOutputStream(filename));
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = in.read(buffer)) != -1) {
stream.write(buffer, 0, len);
}
if(stream!=null) {
stream.close();
}
} else {
showToast("replace: "+replace.toString()+" , file exists " + f.exists());
if(f.exists()== false) {
OutputStream stream = new BufferedOutputStream(new FileOutputStream(filename));
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = in.read(buffer)) != -1) {
stream.write(buffer, 0, len);
}
if(stream!=null) {
stream.close();
}
}
}
//Do something
} catch (IOException e) {
// TODO: handle exception
logonscreen("exception at Save File:" +filename + "exception" + e.getMessage());
// showToast("exception:" + e.getMessage());
} catch (Exception e) {
logonscreen("exception at Save File:" + e.getMessage());
// showToast("exception:" + e.getMessage());
e.printStackTrace();
}
}

Cannot download video file with android emulator

Here's the code to download a 3pg video file. Maybe one can give me an idea about what's wrong with it. I really need help. Can't get it to download the file:
Blockquote
protected String doInBackground(String... sUrl) {
byte[] data = new byte[1024];
int count = 0;
FileOutputStream fos = null;
BufferedOutputStream output = null;
try {
URL url= new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
Log.v("URL"," " + connection.getURL());
Log.v("File ", "length = " + connection.getContentLength());
// download the file
BufferedInputStream input = new BufferedInputStream(connection.getInputStream());
File f = new File(Environment.getExternalStorageDirectory().getPath() + "/twokids.3gp");
f.setWritable(true,true);
try {
fos = new FileOutputStream(f);
} catch (FileNotFoundException fnfe) {
fnfe.getStackTrace();
} catch (SecurityException se) {
se.getStackTrace();
}
output = new BufferedOutputStream(fos);
while ((count = input.read(data)) != -1) {
Log.v("Count="," " + count);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
Log.v("Download","Finished");
} catch (IndexOutOfBoundsException iobe) {
iobe.getStackTrace();
} catch (IOException ioe) {
ioe.getStackTrace();
} catch (NullPointerException npe) {
npe.getStackTrace();
}
catch (Exception e) {
e.getStackTrace();
}
return null;
}
And strangely enough, sometimes the method connection.getContentLength() returns -1 instead of the file length.

Categories

Resources