Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 12 of 12

Thread: Using FileOutputStream to save array of bytes

  1. #1
    Junior Member
    Join Date
    Mar 2014
    Posts
    17
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Using FileOutputStream to save array of bytes

    Hi, I am having trouble implementing FileOutputStream to save an array of data. In this code, I implement a loop which counts to 9, stores the counter values in a byte array, then writes the array to a text file on an Android device (4.2.2). The code runs and I am able to save a text file on the Android external storage and open it up on the device to view the contents. However I cannot get it to save as numerical numbers. With the code below, I am seeing two symbols of "?" which are inside of a diamond. Every other way I tried it would return a blank document. I seem to be missing something fundamental about how the "write" function of FileOutputStream saves data. If someone can help me with this data handing I would appreciate it, thank you.

     
    package com.example.sdcardsavetest;
     
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.concurrent.TimeUnit;
    import com.example.sdcardsavetest.R;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;
    import android.app.Activity;
    import android.os.Bundle;
    import android.os.Environment;
     
     
    public class MainActivity extends Activity {
     
    	File myExternalFile;
    	private String filename = "MySampleFile.txt";
    	private String filepath = "MyFileStorage";
    	TextView TextView;
    	byte[] array = new byte[100];
    	byte x = 1;
     
    	 @Override
    	 public void onCreate(Bundle savedInstanceState) {
    	     super.onCreate(savedInstanceState);
    	     setContentView(R.layout.activity_main);
    	     TextView = (TextView)findViewById(R.id.TextView);
    	     Button startButton = (Button)findViewById(R.id.button);
    	     Button saveToExternalStorage = (Button) findViewById(R.id.saveExternalStorage);
     
    		 if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {  
    			   saveToExternalStorage.setEnabled(false);
    			  } 
    			  else {
    			   myExternalFile = new File(getExternalFilesDir(filepath), filename);
    			  }
     
    		 saveToExternalStorage.setOnClickListener(new View.OnClickListener() {
    			 @Override
    	         public void onClick(View v) {
    				 try{
    					FileOutputStream fos = new FileOutputStream(myExternalFile);
    					System.out.println(array);//debugging
    				        fos.write(array);
    				        fos.close();
     
    				 }
    				    catch (IOException ex) { }
    				 }
    		 	 });	 
     
    		 startButton.setOnClickListener(new View.OnClickListener() {
    	         @Override
    	         public void onClick(View v) {
    	             loop();
    	         }
    	     });
    	 }
     
    	 private static boolean isExternalStorageReadOnly() {  
    		  String extStorageState = Environment.getExternalStorageState();  
    		  if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {  
    		   return true;  
    		  }  
    		  return false;  
    		 }  
     
    		 private static boolean isExternalStorageAvailable() {  
    		  String extStorageState = Environment.getExternalStorageState();  
    		  if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {  
    		   return true;  
    		  }  
    		  return false;  
     		 } 
     
    void loop(){
     
    	runOnUiThread(new Thread(new Runnable(){
     
         public void run(){
     
        	 for (byte i = 1; i < 10; i++){
        		array [x] = i;
    			TextView.setText(String.valueOf(i));
    			x++;
     
    			try {
              	  TimeUnit.MILLISECONDS.sleep(1000); 
    		          	} 	
                       catch (InterruptedException ie) {}
     
    			  }
         	   }
           }));
    	} 
    }
    Last edited by baseball07; August 18th, 2014 at 08:26 PM.


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    6,329
    My Mood
    Mellow
    Thanks
    253
    Thanked 781 Times in 766 Posts

    Default Re: Using FileOutputStream to save array of bytes

    Thread moved.

  3. #3
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,372
    Thanks
    183
    Thanked 836 Times in 779 Posts
    Blog Entries
    5

    Default Re: Using FileOutputStream to save array of bytes

    I am seeing two symbols of "?" which are inside of a diamond
    It is unclear, at least to me, how you 'see' the file contents. Do you display the file contents elsewhere? How are you reading the file? How do you know this is a writing problem rather than a reading problem?

  4. The Following User Says Thank You to copeg For This Useful Post:

    baseball07 (August 21st, 2014)

  5. #4
    Junior Member
    Join Date
    Mar 2014
    Posts
    17
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Using FileOutputStream to save array of bytes

    I am able to create a text file and save it to the external storage on the device. I use the file explorer on the device to locate and open the file. I updated the original post with this information.

  6. #5
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,372
    Thanks
    183
    Thanked 836 Times in 779 Posts
    Blog Entries
    5

    Default Re: Using FileOutputStream to save array of bytes

    The data is being saved as binary - try writing in text form (eg convert the byte to a String). As suggested in the API for FileOutputStream:

    FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter.

  7. The Following User Says Thank You to copeg For This Useful Post:

    baseball07 (August 21st, 2014)

  8. #6
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    906
    Thanks
    0
    Thanked 169 Times in 150 Posts

    Default Re: Using FileOutputStream to save array of bytes

    If you write raw bytes you wont see them displayed as numbers in a text document. This is because every character of a text document is usually one byte or larger in size (depending on the encoding). If you want to display the number 123 you would thus need at least 3 bytes or more.
    If you want to write out numbers that are humanly readable write them as a string.

  9. The Following User Says Thank You to Cornix For This Useful Post:

    baseball07 (August 21st, 2014)

  10. #7
    Junior Member
    Join Date
    Mar 2014
    Posts
    17
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Using FileOutputStream to save array of bytes

    Thanks for all the suggestions, I actually have done that initially (converted bytes to String) and still did not come out as numbers, which is what prompted my initial post. When I convert to String my text file contains a line of characters as [B@41449958 when I implement the write function as:

    fos.write(array.toString().getBytes());

    Is there something about the FileOutputStream that I am missing?

  11. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,324
    Thanks
    56
    Thanked 2,374 Times in 2,345 Posts

    Default Re: Using FileOutputStream to save array of bytes

    [B@41449958
    That is the String returned by the byte array's toString() method.
    To write the contents of the array use: fos.write(array);
    FileOutputStream is meant for writing streams of raw bytes
    You should use a different class and method to write text.

    For testing: write a small simple program that will compile and execute on the desk top and that can be posted here to show what you are trying to do. Testing Android code is too cumbersome.
    If you don't understand my answer, don't ignore it, ask a question.

  12. The Following User Says Thank You to Norm For This Useful Post:

    baseball07 (August 21st, 2014)

  13. #9
    Junior Member
    Join Date
    Mar 2014
    Posts
    17
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Using FileOutputStream to save array of bytes

    Ok thanks, actually I had used: fos.write(array); in my initial post and it resulted in a series of "?". This is a test code, however I will design a test code which executes on the desktop to see if I get the same thing.

    Which class and method should I use then?

  14. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,324
    Thanks
    56
    Thanked 2,374 Times in 2,345 Posts

    Default Re: Using FileOutputStream to save array of bytes

    The Writer classes like FileWriter and OutputStreamWriter might work.
    If you don't understand my answer, don't ignore it, ask a question.

  15. The Following User Says Thank You to Norm For This Useful Post:

    baseball07 (August 22nd, 2014)

  16. #11
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,372
    Thanks
    183
    Thanked 836 Times in 779 Posts
    Blog Entries
    5

    Default Re: Using FileOutputStream to save array of bytes

    fos.write(array.toString().getBytes());
    As norm pointed out, using the toString() method of array will use the default toString() method - see Object (Java Platform SE 7 )
    Loop over the array and write each value as a String using the appropriate writer class that is meant for text

  17. The Following User Says Thank You to copeg For This Useful Post:

    baseball07 (August 22nd, 2014)

  18. #12
    Junior Member
    Join Date
    Mar 2014
    Posts
    17
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Using FileOutputStream to save array of bytes

    Guys, this was a great help thank you. The following code worked:

     
    PrintWriter save = new PrintWriter(myExternalFile);
    save.println(Arrays.toString(array));
    save.close();

Similar Threads

  1. Save array to text file
    By JGW in forum What's Wrong With My Code?
    Replies: 11
    Last Post: February 6th, 2013, 10:45 AM
  2. Save Textfield to an Array
    By NorahPoly in forum What's Wrong With My Code?
    Replies: 9
    Last Post: June 13th, 2012, 08:27 PM
  3. Blackberry Api: Writing an array of bytes to a file
    By jules0075 in forum File I/O & Other I/O Streams
    Replies: 5
    Last Post: July 18th, 2011, 02:50 PM
  4. [SOLVED] How to specify FileOutputStream location?
    By Hallowed in forum Java Theory & Questions
    Replies: 7
    Last Post: May 29th, 2011, 07:36 PM
  5. convert vector to array of bytes
    By chopficaro in forum Java Theory & Questions
    Replies: 1
    Last Post: May 3rd, 2010, 12:00 PM