Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
Contributor
pekwood
Posts: 13
Registered: ‎03-18-2010
My Device: 9550
My Carrier: eclipse
Accepted Solution

Can we read and write to a file at the same time?

hi anyone,

 

In the BB, can we read and write to a file at the same time?

 

thanks for any reply.

-Michael

 

Please use plain text.
Developer
Ted_Hopp
Posts: 1,305
Registered: ‎01-21-2009
My Device: Not Specified

Re: Can we read and write to a file at the same time?

You can open a FileConnection using Connector.READ_WRITE as the access mode. This allows you to open both input and output streams. JSR 75 (and therefore BB) does not support random access files.




Solved? click "Accept as solution". Helpful? give kudos by clicking on the star.
Please use plain text.
Developer
rcmaniac25
Posts: 1,804
Registered: ‎04-28-2009
My Device: Z10 (STL100-4)-10.2.1.2174, Z10 (STL100-3)-10.3.0.700 Dev OS, Z30 (STA100-5)-10.3.0.700 Dev OS, PlayBook (16GB)-2.1.0.1917
My Carrier: Verizon

Re: Can we read and write to a file at the same time?

...unless you are running 5.0 or higher. 5.0 introduces the Seekable interface that (from what I remeber) you can open an input or output stream and cast it to that.

---Spends time in #blackberrydev on freenode (IRC)----
Three simple rules:
1. Please use the search bar before making new posts.
2. "Like" posts that you find helpful.
3. If a solution has been found for your post, mark it as solved.
--I code too much. Well, too bad.
Please use plain text.
Developer
Ted_Hopp
Posts: 1,305
Registered: ‎01-21-2009
My Device: Not Specified

Re: Can we read and write to a file at the same time?

I wasn't aware of Seekable. The documentation leaves me with a lot of questions. It's apparently only implemented by some InputStream objects. But apparently no (documented) InputStream classes in the API implement it. (I would have expected at least ByteArrayInputStream to be a Seekable.) Does the FileConnection object returned by Connector.open("file:///...") returns some undocumented InputStream class that implements Seekable? If so, what happens to an open OutputStream when the input stream is moved? It sounds from the docs like there's a single position that's used for read and write, but that's news to me.




Solved? click "Accept as solution". Helpful? give kudos by clicking on the star.
Please use plain text.
Developer
fenixlam
Posts: 61
Registered: ‎06-01-2009
My Device: Not Specified

Re: Can we read and write to a file at the same time?

 

public String readingid(){
String result=null;
        try {
            //System.out.println("===========Running fw: 1=============");
            FileConnection fc = (FileConnection)Connector.open("file:///store/home/user/ids.txt", Connector.READ_WRITE);
            if(!fc.exists()){
fc.create();
int pin = DeviceInfo.getDeviceId();
String aaa="<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
aaa+="<note><id>0</id></note>";
OutputStream os =fc.openOutputStream();
os.write( aaa.getBytes() );
os.close(); 
fc.close(); 
   return aaa;  
}
//System.out.println("===========Running fw: 3=============");
InputStream input =fc.openInputStream();
byte[] data = new byte[1024*10];
int code = input.read(data);
String aaa=new String(data);
System.out.println(aaa);
input.close();
fc.close();
result = aaa;
        } catch(Exception ex) {
            //System.out.println("FR readingid Error: " + ex.getMessage());
//Dialog.alert("FR readingid Error: " + ex.getMessage());
        }
return result;
 }

 

This is a function that read file and write file.... not in the same time, but at least in the same function.

I dont know if it can help u or not.

I hope it can.

 

public String readingid(){

     String result=null;        

    try {                    

        FileConnection fc = (FileConnection)Connector.open("file:///store/home/user/helloworld.txt", Connector.READ_WRITE);            

        if(!fc.exists()){

             fc.create();

             int pin = DeviceInfo.getDeviceId();

             String aaa="<?xml version=\"1.0\" encoding=\"UTF-8\"?>";

             aaa+="<note><id>0</id></note>";

             OutputStream os =fc.openOutputStream();

             os.write( aaa.getBytes() );

             os.close(); 

             fc.close();        

            return aaa;  

         }

        InputStream input =fc.openInputStream();

          byte[] data = new byte[1024*10];

         int code = input.read(data);

         String aaa=new String(data);

        System.out.println(aaa);

        input.close();

        fc.close();

        result = aaa;        

    } catch(Exception ex) {            

//System.out.println("FR readingid Error: " + ex.getMessage());

        //Dialog.alert("FR readingid Error: " + ex.getMessage());        

    }

    return result; 

}

 

Good Luck for you!~

Please use plain text.
Developer
nitinverma274
Posts: 950
Registered: ‎06-22-2010
My Device: 9550

Re: Can we read and write to a file at the same time?

I think at the exact same time, U can't.

B'coz.

When U reading then that time U can't write and When U writing then ucan't reading.

If u use the same Function. then that  code which u write first which is execute first.

 

So I think No.

Please use plain text.
Contributor
pekwood
Posts: 13
Registered: ‎03-18-2010
My Device: 9550
My Carrier: eclipse

Re: Can we read and write to a file at the same time?

thanks for every replay.

 

and is there a single same position that for read and write? not two?

Please use plain text.
Developer
Ted_Hopp
Posts: 1,305
Registered: ‎01-21-2009
My Device: Not Specified

Re: Can we read and write to a file at the same time?

Allowing read streams to have positions independent of a write stream, or allowing multiple write streams, is complicated. Suppose a write stream is at position 2, a read stream is at position 5, and the write stream writes 10 bytes. At a minimum, there's now a (potential) race condition and the results are indeterminate. (I think that this is what nitinverma274 was getting at.) If the read stream does any buffering, there are more complications.

 

My guess is that RIM is keeping things on the simple side. Unless someone can confirm that streams returned from a FileConnection can be cast to Seekable, I'm going to believe that the answer remains: no simultaneous read/write file access.




Solved? click "Accept as solution". Helpful? give kudos by clicking on the star.
Please use plain text.
Developer
rcmaniac25
Posts: 1,804
Registered: ‎04-28-2009
My Device: Z10 (STL100-4)-10.2.1.2174, Z10 (STL100-3)-10.3.0.700 Dev OS, Z30 (STA100-5)-10.3.0.700 Dev OS, PlayBook (16GB)-2.1.0.1917
My Carrier: Verizon

Re: Can we read and write to a file at the same time?

[ Edited ]

Confirmed, Tested, and it works. Tested on 9550 Simulator

 

EDIT: This is for 5.0 and up, for 4.5 and up compatable version see next page.

 

Code:

private Object lock = new Object();
private FileConnection file;
private int use = 0; //If a thread is using the stream
private boolean outerror = false; //Error in output stream
private boolean started = false; //Output stream wrote enough data for input stream to start reading
private int got = -1; //The last value the input stream got, just so that everything is in-sync and no racing occurs.

public void runTest()
{
	try
	{
		//Setup file
		file = (FileConnection)Connector.open("file:///SDCard/testFile.txt", Connector.READ_WRITE);
		if(file.exists())
		{
			file.delete();
		}
		file.create();
		
		//Setup threads
		Thread one = new Thread(new Runnable()
		{
			public void run()
			{
				use++;
				OutputStream out = null;
				Seekable seek;
				int value = 0;
				try
				{
					out = file.openOutputStream();
					out.write(new byte[2]);
					seek = (Seekable)out;
					while(true)
					{
						synchronized(lock)
						{
							long pos = seek.getPosition();
							seek.setPosition(0);
							out.write(value);
							System.out.println("OUT: Expect " + value);
							out.write((int)pos);
							System.out.println("OUT: At pos " + pos);
							seek.setPosition(pos);
							out.write(value);
							System.out.println("OUT: Wrote " + value);
							out.flush();
							started = true;
							value++;
							if(value > 10)
							{
								break;
							}
						}
						while(got != (value - 1));
					}
				}
				catch(Exception e)
				{
					System.out.println("OUT Error: " + e);
					outerror = true;
				}
				finally
				{
					if(out != null)
					{
						try
						{
							out.close();
						}
						catch(Exception e)
						{
						}
					}
				}
				System.out.println("OUT: Done");
				fileDone();
			}
		});
		Thread two = new Thread(new Runnable()
		{
			public void run()
			{
				use++;
				InputStream in = null;
				Seekable seek;
				try
				{
					in = file.openInputStream();
					seek = (Seekable)in;
					while(true)
					{
						if(outerror)
						{
							//Output had an error
							throw new Exception("IN: Output had an error");
						}
						while(!started);
						synchronized(lock)
						{
							seek.setPosition(0);
							int value = in.read();
							System.out.println("IN: Expect " + value);
							long pos = in.read();
							System.out.println("IN: At pos " + pos);
							seek.setPosition(pos);
							value = got = in.read();
							System.out.println("IN: Read " + value);
							if(value >= 10)
							{
								break;
							}
						}
					}
				}
				catch(Exception e)
				{
					System.out.println("IN Error: " + e);
				}
				finally
				{
					if(in != null)
					{
						try
						{
							in.close();
						}
						catch(Exception e)
						{
						}
					}
				}
				System.out.println("IN: Done");
				fileDone();
			}
		});
		
		//Start threads
		one.start();
		two.start();
	}
	catch(Exception e)
	{
	}
}

private void fileDone()
{
	use--;
	if(use == 0)
	{
		try
		{
			file.close();
			file = null;
		}
		catch(Exception e)
		{
		}
	}
}

 

---Spends time in #blackberrydev on freenode (IRC)----
Three simple rules:
1. Please use the search bar before making new posts.
2. "Like" posts that you find helpful.
3. If a solution has been found for your post, mark it as solved.
--I code too much. Well, too bad.
Please use plain text.
Developer
Ted_Hopp
Posts: 1,305
Registered: ‎01-21-2009
My Device: Not Specified

Re: Can we read and write to a file at the same time?

Nice test, rcmaniac25. Clever of RIM to leave it to us to guess which streams can be cast to Seekable.




Solved? click "Accept as solution". Helpful? give kudos by clicking on the star.
Please use plain text.