reading and writing to the file on SD card

I am currently using this code to read and write to files (credit is not because of me - I found these on the Board somewhere):

   private void writeFile(String data, String filePath)
    {
        try
        {
            FileConnection conn = (FileConnection)Connector.open(filePath,Connector.READ_WRITE);
            if (!conn.exists())
            {
                Dialog.alert("No File Present Click to Create");
                conn.create();
            }

            OutputStream out = conn.openOutputStream();
            byte[] b = data.trim().getBytes();
            String sb = new String(b);
            System.out.println("Bytes to String: " + sb);

            if(sb.length() == 0 )
                System.out.println("String length is zero");
            else
                System.out.println("String length is not zero" + sb.length());

            if(conn.canWrite())
            {
                Dialog.alert("Writing");
                out.write(b,0,sb.length());
            }
            else
                System.out.println("Cannot write to this file");

            System.out.println("File Size is : "+ conn.fileSize());
            out.flush();
            out.close();
        }
        catch(Exception io)
        {
            test.setText("Exceptino Thrown from File" +io);
        }

    }

    private String readFile(String filePath)
    {
        try
        {
            FileConnection fconn = (FileConnection)Connector.open(filePath, Connector.READ);
            if (fconn.exists())
            {
                InputStream input = fconn.openInputStream();

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int j = 0;
                while((j=input.read()) != -1) {
                    baos.write(j);
                }
                byte[] data = baos.toByteArray();
                input.close();

                String output = new String(data);
                System.out.println("Output" + output);

                fconn.close();
                return output;
            }
            else
            {
                System.out.println("File does not exist");
                fconn.close();
                return null;
            }
        }
        catch (Exception ioe) {

           System.out.println("Error:   " + ioe.toString());
           return null;
        }

    }

When I try to write a string to a file and then read it again, I get a NullPointerException. When I check the folder that mimicks card SD card on my pc, there is no file created. is the above code ok?

P.S. I use a simulator of the OS 5.0 and the SD card directory is configured to be somewhere on my desk.

It is incredibly baroque and inefficient code for a simple job; be happy that you do not claim credit for it.

A problem may be that the FileConnection in writeFile is not closed. I would rewrite the mess like this (leaving a part of the diagnostic output):

private void writeFile(String data, String filePath) {  data = data.trim();  OutputStream out = null;  FileConnection conn = null;  try {     conn = (FileConnection) Connector.open(filePath,Connector.READ_WRITE);    if (!conn.exists()) {      conn.create();    }    OutputStream out = conn.openOutputStream();    // it might be advisable to specify an encoding on the next line.    out.write(data.getBytes());  } catch (Exception io) {    test.setText("Exception Thrown from File " + io);  } finally {    if (out != null) try { out.close(); } catch (IOException ignored) {}    if (fconn != null) try { fconn.close(); } catch (IOException ignored) {}  }}

private String readFile(String filePath) {  String result = null;  InputStream input = null;  FileConnection conn = null;  try {    fconn = (FileConnection) Connector.open(filePath, Connector.READ);    if (fconn.exists()) {      input = fconn.openInputStream();      byte[] bytes = IOUtilities.streamToBytes(input);      // it might be advisable to specify an encoding on the next line.      result = new String(bytes);    } else {      System.out.println("File does not exist");    }  } catch (Exception ioe) {    System.out.println("Error: " + ioe.toString());  } finally {    if (input != null) try { input.close(); } catch (IOException ignored) {}    if (fconn != null) try { fconn.close(); } catch (IOException ignored) {}  }  return result;}

Tags: BlackBerry Developers

Similar Questions

  • simultaneous reading and writing on a PDM file

    I found similar discussions on here, but none that satisfied my problem. I'm running several loops within a vi, which writes data in a permanently .tdms file. Another loop to finish its task from the start in a test, and I want to transition this loop so that it accesses the file writing and started writing on a network. It also enables me to check that the data is being stored in the file and that it is corrupt.

    I started with just the basics, but when I pass the second loop to read the file that is is always written off mistakes, saying that she met at the end of the file. It does if I put the count 1, -1 or anything in between. It illuminates, however, the end of the file output.

    I have the entry in the file tdms on PDM read wired to a local variable, just as I do writing PDM, they all have both read the same thing and I get an iterations of a data value of the reading, so, apparently, file access is no problem. And I have to someone who cringed to local variables, ensure that reading and writing are not activated until the local variable is updated.

    Try to set the "group name" entry on «TDMS read» If you write more than one group, you can use "View the contents of the DDHN" in order to get a list of groups.

    Herbert

  • simultaneous reading and writing files TDMS

    A customer had a program written in 8.6; the programmer is no longer available and I'm looking to debug intermittent problems.

    N - channels of data is acquired and streamed to a PDM file. The operator can select a channel to view data in real time, but the display is one scope table displaying 15 seconds worth of data and when switching of channels the program "returns" display with the last 15 seconds of a data value of the new string (barrier data extracted from the TDMS file).

    What I notice here, aside from using sloppy cluster error, is that both references are open in the file - one for writing data and the other for recovery data. Is this a good practice? is it necessary or one reference supports the reading and writing? Is this a possible source of problems?

    thanx

    lmd2

    You can do the same thing with a single file reference.

    The issue of not being able to see the data that was written after the reading of reference has been opened is known for having refnums to open in two different processes, but not in the same executable or VI.

    Herbert

  • Read and write to the local XML file

    Hello

    I'm trying to understand how to use the xml files saved locally. My goal is to create an xml file in the repository of the application (which has read/write permissions), add data in this file xml and re - register so that it can be retrieved whenever this is necessary.

    I want to store xml data are farily short; It has the following structure:

    
        x
        x
        x
        x
        x
        x
        x
        x
        x
        x
    
    
    
    ...etc.
    

    I read a few articles about recording and writing in a file like this, but none of them does not seem to work. I hope someone could provide me with the code to do this.

    Thank you.

    Try:

    ///////////////////////////////////////////////////////////////////////

    public public static function Store (name: String, data: String): void

    {

    var file: file = File.applicationStorageDirectory.resolvePath (name);

    var file_stream: FileStream = newFileStream();

    file_stream. Open (file, FileMode.WRITE);

    out of the var : String = '\n';

    output of +=;

    output = output.replace (\n/g, File.lineEnding);

    file_stream.writeUTFBytes (output);

    file_stream. Close();

    }

    //////////////////////////////////////////////////////////////////////////

    public public static function Get (name: String): XML

    {

    var config: XML = null;

    var file: file = File.applicationStorageDirectory.resolvePath (name);

      if (file.exists)

    {

    var file_stream: FileStream = new FileStream();

    file_stream. Open (file, FileMode.READ);

    config = new XML (file_stream.readUTFBytes (file_stream.bytesAvailable));

    file_stream. Close();

    }

    return config;

    }

  • Reading and writing a file

    I'm trying to read and write to a file so that I can store a string array and a double in my application, but I came out a few problems; Firstly when I put my path in the constant path he will say that the file is not there never be (so I have to force the issue and when the application requests a file I have to browse and add files), secondly when I run the program and it reads in the file it does not display the strings or double immediately instead , I must hit the submit button and what they finally, finally arrive when I reset my values in the .txt files and put in my thong and double and press on submit table jumps in one place and starts at index 1 (array [1]) if anyone can help I would appreciate it a lot.

    Here is my code:

    That's what I wanted to say on the structure of the event and it should take your second problem.  I don't see the third one.  I saw no flicker, but I have a slight vision problem which means I do not waver.  So he can sparkle.  Or maybe not.

  • How can I fix excerpt: error writing to the file and an unstable WiFi connection

    original title: How can I fix excerpt: error writing to the file

    Hello, I do not know anythingon fixing of my computer when I have problems. I looked at all the research sites and assistance, and none of them helped me with these problems and im getting ready to launch her aspire one mini laptop computer. im running xp and I bought it used and it has done this from day one. 2 weeks ago, that I got it. Please can you help me.

    How can I fix excerpt: error writing to the file C:docume~1\user\local~1\temp\nsvc.tmp\conduit-left.bmp

    and im having problems with my connection remaining on the port wireless what do I do, I can solve this problem too because I cannot even be in line for more then 5 minutes with the duty to stop and start over or repair the connection.

    For the first question, try to go to start | Programs | Accessories | System Tools | Disk Cleanup and that should clear of junk.  Then click Start | Run and type msconfig and disable the startup items, that you don't need, as many programs decide that they must run at startup and clutter the machine when they do not need to.  Also perform a defragmentation of the disk (under system tools also).  See if that helps with performance and other issues.

    Steve

  • QFile writing in the file and trash to the first line

    Hello. Got this code, writing to the file

    RPL - QNetworkReply

       QString workingDir = QDir::currentPath();
        qDebug() << workingDir;
        QFile friendsData("data/friends.json");
        friendsData.open(QIODevice::ReadWrite | QIODevice::Text);
        QDataStream in(&friendsData);
        QByteArray ans = rpl->readAll();
        qDebug() << ans;
        in << ans;
        friendsData.close();
    

    And as a result I got

    With xml - the same thing.

    It was easy.
    * beep *, I forfot QTextStream rather QDataStream

  • I downloaded a trial version of Adobe DC but don't want I want just the free reader. I can't remove it as he advises Adobe application Manager and outlook use the files. I closed, restarted and set it up again, but it does not work. How can I delete

    I downloaded a trial version of Adobe DC but don't want I want just the free reader. I can't remove it as he advises Adobe application Manager and outlook use the files. I closed, restarted and set it up again, but it does not work. How can I remove the program

    Use of the Adobe Creative Cloud cleaning tool to solve installation problems can help

  • I recently tried to open a new pdf file using an existing program Acrobat Reader and it changed the extensions of all programs and .pdf desktop icons, making them unusable.  I uninstalled Reader and extensions have been fixed.  But when I installed the dr

    I recently tried to open a new pdf file using an existing program Acrobat Reader and it changed the extensions of all programs and .pdf desktop icons, making them unusable.  I uninstalled Reader and extensions have been fixed.  But when I installed the drive again - the latest version (DC) it happened again.  How can I fix it?  I am on Windows 7

    Hi donaldm78047015,

    Try the solution mentioned in this KB doc. https://helpx.Adobe.com/Acrobat/KB/application-file-icons-change-Acrobat.html

    Kind regards

    Nicos

  • How can I hide the page thumbnails navigation bar initially to the top of Adobe Reader and open a pdf file?

    How can I hide the page thumbnails navigation bar initially to the top of Adobe Reader and open a pdf file? I couldn't find this option on the Preferences tab? Thank you

    Under Edit - Prefs. - Documents check the box that says "Restore last display settings when reopening documents." Hide the Pages panel manually, and the next time that you open the file it should have disappeared.

  • How to read the data of BLOB and save to the file system

    Hi friends.

    I have called DEMO table there image stored as a BLOB. now my requirement is to know how to read the data of BLOB and saved in the file system. is there a procedure
    to read the blob object and stored in the file system. pls suggest me with an example.
    Thank you

    HI - don't know what version you have, but have a read through this:

    http://www.Oracle-base.com/articles/9i/ExportBlob9i.php

    Hoek link is to import the blobs in the db, it is export, to a file.

  • "Error 1310" error writing to the file: c:\config.msi\f2046.rbf "while trying to install Adobe.

    Atitle: how to fix error 1310?

    We have vista and I get this error when I try to download adobe reader: 1310.error error writing to the file: c:\config.msi\f2046.rbf. How can I fix this error? Also had trouble to update old adobe, so I uninstalled, so now I have no adobe reader.

    Hello

    -Is the issue limited only when trying to install Adobe programs?
    -Did you do changes on the computer before this problem?
     
    Method 1: Run the FIXIT from Microsoft from the link below and check if the problem persists.
    Solve problems with programs that cannot be installed or uninstalled
     
    Method 2: I also suggest you to see the link below and check if that helps.
    Update errors. Acrobat, Reader | Windows
     
    Hope this information helps.
  • After effects error: rendering error while writing to the file. The disk is full.

    Hello

    I tried to return a video in AE CC 2014, with RGB + Alpha because I wanted to keep the background transparent (rotoscoped) so that I can then use it in first.

    I chose to export to QuickTime, with uncompressed 8-bit.

    After he made it for a little while, I had a pop up window saying

    After effects error: error in rendering when writing to the file "E:... blabla". The disk is full. The file may be damaged or corrupted. (- 1610153463).

    I read a thread posted in the forums, but I don't understand the solution here... What is a POD?

    I have a Win7 Ultimate, x 64. A lot of disk space and 16 GB of RAM.

    Please help, I canoot go further in my project with this bug...

    Jaywaii

    Is the drive in FAT32 formatted accidentally? If so, you can only restore up to 4 GB for a single file. Try to make a TIFF sequence instead. Tip of litte - press the LZW compression checkbox in the options for a lossless compression format, this allows you to keep the path file size down.

  • Questions about serial port read and write at the same time

    Hi I create a user interface for the communication serial port, where there are essentially 2 front panels, where the user enters commands one and the other where the prints of UART is delivered. I thought initially using a state machine but the reading and writing may be independent sometimes and so I can't rely on States. I searched a bit on the forum and he left me even more confused. Help, please.

    (1) in a thread that sessions visa duplicated has been used for writing and reading at the same time, is it recommendable? How will this affect performance?

    (2) essentially when the vi is reading data are it must constantly view as well, however, someone said that it takes too much memory to use shift registers, so how do I go about this? If using a State in queue after the loop of reading it affects the playback loop and be sequential?

    In addition anyway is to move the cursor to the latest data from the indicator

    (3) for the control of the user input, assumes that the user has entered an order in the control and press ENTER, then writing visa is launched, but if it comes in another string and press enter then write must be called again... is - it possible? will detect the previous commands in the control of compensation?

    (4) according to my understand the expectation for the event do not monopolize resources and writing can go in parallel, am I right?

    Thank you. I have attached a very basic vi which took me to the point, but I want to make it more robust. Please help especially in the part of the user interface.

    su_a,

    (1) you can have only one session to a port. Several UART can handle full duplex so performance is not affected.  At flow rates of high data and large amounts of data, buffering and latencies of BONE can become a problem.

    (2) who told you that shift registers using too much memory? Shift registers are usually the best way to transfer data from one iteration to another. String concatenation inside a loop (registry to offset or not) causes the chain to develop and may require re-allocation of memory.  Your VI never clears the string so its cold length become very large.

    Generally, you do not have an active cursor on an indicator.  If you want to always display the most recently received characters and turn on the vertical scroll bar use a property node to keep scrolls to the bottom.  This can be annoying for users if they attempt to manually move the scroll bar and find that the program continues to move it back automatically.

    (3) if the user has changed the value in the chain of command, when he hits enter the modified value event fires.  Simply strike brace does not change the value and does not trigger the event.  Not control need to be erased, but the value that he has to change.  If you want to send the same command again, have a button send a command may be a better choice.

    (4) write is a case of the event.  It is not in parallel with anything.  The structure of the event do not monopolize resources.  The other loop will run while it waits.

    The event loop will not stop when you press the STOP button. Probably it wll take two command: change events of value after JUDGMENT before any loop stops.  Replace the Timeout event (which never expires) with a STOP: value change event and a real wire of this judgment to the Terminal endpoint.  Remove the local variable.  Make mechanical locking when released.

    Lynn

  • Error message - error 1310: error writing to the file: C:\Config.Msi\95cd7a.rbf

    I get the error message on the software updates: error 1310: error writing to the file: C:\Config.Msi\95cd7a.rbf.  Make sure you have access to this directory.  How can I fix it?  Thank you

    Hello

    ·          What version of the operating system is running on your computer?

    ·          What software you are trying to update?

    However, try the following steps:

    Unregister and re-register Windows Installer.

    a. Click Start and then click Run.

    (b) in the Open box, type msiexec /unreg and then press ENTER.

    c. Click Start and then click Run.

    (d) in the Open box, type msiexec/regserver, and then press ENTER.

Maybe you are looking for