Skip to main content

How to Copy a file on Phone using JSR 75?

2 replies [Last post]
kashi1982
Offline
Joined: 2008-12-16
Points: 0

Hello Members,

Please help answer this question.

How to Copy a file on Phone using JSR 75? Please let me know at the earliest.
Thanks.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
sfitzjava
Offline
Joined: 2003-06-15
Points: 0

Well as with everything JavaME, there is a 101 ways to do this wrong, and one way the sometimes works. :)

Now it depends on how you want to copy the file, is this file on a server, is it on a desktop that you connect to via bluetooth or USB cable, or is this from one part of the file system to another?

In the case of the server (and for that matter BT or USB), you will want to setup a connection and get an inputstream. The inputstream you will read the data from into a buffer, and write that buffer to a FileConnection looping through this process of reading buffers from the inputstream and writing them to the fileconnection outputstream.

It would look something like this. (FYI.. this is a quick paste and mod of code I use but is over simplified removing some validations and range tests that should be used in professional code. this is only and example.)

// call method as Follows:
// copyFile("http://mydomain.com/getFile?name=file.txt", "file:///Others/file.txt");

public boolean copyFile(String _url, String _toFile)
{
HttpConnection hc = null;
InputStream is = null;
OutputStream os = null;
FileConnection fc = null;

try
{
try
{
hc = (HttpConnection) Connector.open(_url);
int respCode = hc.getResponseCode();
if ( respCode != 200) { return false; }
is = hc.openInputStream();
if (is != null)
{
fc = (FileConnection) Connector.open(_toFile);
if (fc.exists()){ fc.delete(); }
fc.create();
os = fc.openOutputStream();
if (os != null)
{ // download bytes to buffer and write buffer to file system.
int byteCnt = 0;
byte[] buffer = new byte[2048];
while ((byteCnt = is.read(buffer,0,buffer.length)) >= 0)
{
os.write(buffer,0,byteCnt);
os.flush();
}
}else // no file output
{ return false; }
}else // no inputstream
{ return false; }
}finally
{
if (is!=null) { is.close(); is=null; }
if (dos!=null) { dos.close(); dos=null; }
if (fc!=null) { fc.close(); fc=null; }
if (hc!=null) { hc.close(); hc=null; }
}
}catch(Exception e)
{ return false; }
return true;
}

Expectations are that you would have a server with a servlet that took the name parameter and read that file from the local filesystem and streamed it over the connection as the response. Or that you write a desktop service that communicates over BT or serial USB to the device and streams the data through a connection. But those are topics for other forums.

Merry Christmas, :)
-Shawn

kashi1982
Offline
Joined: 2008-12-16
Points: 0

Hello,

Thanks a lot for the answer..

Merry Christmas..

Kashi