What is the proper way to use the write method?

What is the proper way to use the OutputStreams write method? I know the flush() method is automatically called after the write but i cant seem to get any output
to a file. The char array contains characters and upon completion of the for loop the contents of the array is printed out, so there is actually data in the array. But write dosnt seem to do squat no matter what i seem to do. Any suggestions?
import java.io.*;
public class X{
public static void main(String[] args){
try{      
FileReader fis = new FileReader("C:\\Java\\Test.txt"); //read chars
FileWriter fw = new FileWriter("C:\\Java\\Test1.txt"); //read chars
File f = new File("C:\\Java\\Test.txt");
char[] charsRead = new char[(int)f.length()];
while(true){
int i = fis.read(charsRead);
if(i == -1) break;
// fw.write(charsRead); this wont work
// but there is infact chars in the char Array?
for(int i = 0; i < charsRead.length -1 ; ++i){
System.out.print(charRead);
}catch(Exception e){System.err.println(e);}

Sorry to have to tell you this guys but all of the above are broken.
First of all... you should all take a good look at what the read() method actually does.
http://java.sun.com/j2se/1.3/docs/api/java/io/InputStream.html#read(byte[], int, int)
Pay special attension to this paragraph:
Reads up to len[i] bytes of data from the input stream into an array of bytes. An attempt is made to read as many as len[i] bytes, but a smaller number may be read, possibly zero. The number of bytes actually read is returned as an integer.
In other words... when you use read() and you request say 1024 bytes, you are not guaranteed to get that many bytes. You may get less. You may even get none at all.
Supposing you want to read length bytes from a stream into a byte array, here is how you do it.int bytesRead = 0;
int readLast = 0;
byte[] array = new byte[length];
while(readLast != -1 && bytesRead < length){
  readLast = inputStream.read(array, bytesRead, length - bytesRead);
  if(readLast != -1){
    bytesRead += readLast;
}And then the matter of write()...
http://java.sun.com/j2se/1.3/docs/api/java/io/OutputStream.html#write(byte[])
write(byte[] b) will always attempt to write b.length bytes, no matter how many bytes you actually filled it with. All you C/C++ converts... forget all about null terminated arrays. That doesn't exist here. Even if you only read 2 bytes into a 1024 byte array, write() will output 1024 bytes if you pass that array to it.
You need to keep track of how many bytes you actually filled the array with and if that number is less than the size of the array you'll need pass this as an argument.
I'll make another post about this... once and for all.
/Michael

Similar Messages

  • What's the proper way to use reusingView in a custom UIPickerView

    Does anyone have an example of the proper way to use the resuingView parameter when implementing pickerView:viewForRow:forComponent:reusingView: in a UIPickerViewDelegate?
    The documentation states that reusingView is "A view object that was previously used for this row, but is now hidden and cached by the picker view."
    and: "If the previously used view (the view parameter) is adequate, return that. If you return a different view, the previously used view is released. The picker view centers the returned view in the rectangle for row."
    I need to create UILabel views so I can right justify things, and I have that working by always returning my copy of the view, but it seems like things could be made more efficient by returning the view passed to me if it's "adequate". So, how do I tell if the view is adequate?
    I've tried something like this:
    // check to see if the view we're given is a UILabel and return that view
    if ([view isMemberOfClass:[UILabel class]])
    v = (UILabel *)view;
    return v;
    else
    ... return a UILabel instance for this row ...
    But the view I'm being passed is never a UILabel instance. That or I'm not using isMemberOfClass correctly.
    Thoughts anyone?

    - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    iPregnancyAppDelegate *iPregAppDelegate = [[UIApplication sharedApplication] delegate];
    UILabel *pickerLabel = (UILabel *)view;
    // Reuse the label if possible, otherwise create and configure a new one
    if ((pickerLabel == nil) || ([pickerLabel class] != [UILabel class])) { //newlabel
    CGRect frame = CGRectMake(0.0, 0.0, 270, 32.0);
    pickerLabel = [[[UILabel alloc] initWithFrame:frame] autorelease];
    pickerLabel.textAlignment = UITextAlignmentLeft;
    pickerLabel.backgroundColor = [UIColor clearColor];
    pickerLabel.text = @"Put YOUR text here!";
    return pickerLabel;
    Message was edited by: gpmoore

  • What is the proper way to use Siri dictation with punctuation, on iPad with Retina Display?

    What is the proper way to use Siri dictation with punctuation, on iPad with Retina Display?
    Thank you!

    From the iPad User Manual:
    Also:
    no space on ... no space off—to run a series of words together
    smiley—to insert :-)
    frowny—to insert :-(
    winky—to insert ;-)

  • What is the proper way to move the iTunes (v11) Media folder to an external USB HD?

    What is the proper way to move the iTunes (version 11) Media folder to an external USB HD?  I have tried to following listed instructions, but although I can get the songs listed, their locations are not found.

    Tried the option key, but it would not let me select the copied iTunes folder.  Also changed the path for iTunes Media Location folder.  But still iTunes is not happy.  I could try the alias route, but I don't have an iTunes folder that iTunes is happy with to point it to.  All of the songs and even the playlists will come up, but it seems some form of the folder and its files must remain on the internal hard drive.  But I want to move it off because it is out of space.  Any other thoughts?
    I have all of the music etc files what I do not want to lose is the playlists.  I don't care about the play counts.  I would be glad to reimport all of the songs to the newly designated folder, but won't I lose my playlists?
    Thanks for your help.

  • What is the Proper way to nullify the VECTOR after it's scope is over

    I am using Vectors and Array lists at many places in my Web Application, It is neccessary to use them.
    In some processes I m storing bulk amount of data into vector due to that the performance of my application will be decreased, for that I have to nullify the vector after it's scope is over.
    To nullify I m using Vector v = new Vector()
    v.clear().
    The above method is suitable in case of simple object data like strings and other values.
    But I wanna know that If I m using HashMap and storing bulk data in it and then I m storing each HashMap into vector, what is the proper way.
    Does I have to iterate each object of HashMap from vector and set them as null and then set vector as null or directly I can use v.clear() method??
    If any having any answer regarding my question then plz reply your each valuable reply will be appriciable.
    Thanks in advance......!!

    JBOSS2000 wrote:
    Each time in loop a new object of vector is created and each time I m nullifying it. Thats what I m doing.
    Thats why I m nullifying it.
    Even if I'll declare it out side the loop then also for the each iteration I have to nullify it cause what I m doing is I m inserting the data into database in each iteration of loop, So that I think it is must to nullify the objects each time.If it is constructed inside the loop then you do not have to nullify it. If it is constructed outside of the loop and you want to empty it for each iteration then just clear() it.

  • What is the proper way to open the app store  for ios

    Using Air3.1 to develope a game.
    I want to have links on my main menu which will open the iOS app store for a specific application.
    The only way I have found to do this is by opening a url "http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=<THEAPPIDHERE>&mt=8"
    However, while this does work, so to speak, when I try to go back to the application, it starts up as if it had crashed... and it does several "redirects" before it get's where it is eventually going.
    Is there a better/proper way to open the app store?
    Cheers
    dave

    Read this page, especially the later examples:
    http://bjango.com/articles/ituneslinks/

  • 1163R... What is the best way to use the 1163R.

    I need to record voltage on the SCXI 1121 as soon as the 1163R is switched. What is the best way to do this.

    Hi,
    You may want to take a look at following:
    Link 1
    Link 2
    I know my answer is very general. You may want to elaborate on your question and I will try my best.
    Sincerely,
    Sastry

  • Could someone show me the correct way to use the Vector in the code below?

    Would someone mind explaining to me why I am getting a NullPointerException when I run the code below? I initialized the vector in the constructor so it should follow through the whole class right? What would be the right way to do it?
    import java.util.Vector;
    public class AlumniDirectory
        private String faculty;
        private static Vector alumni;
        /** Constructor reads faculty Name and inits new vector **/
        public AlumniDirectory(String facultyIn)
            Vector alumni = new Vector();      
            faculty = facultyIn;      
        /** Method adds a new Alumni to the list **/
        public void addAlumnus(Object o)
            alumni.addElement(o);
        /** Method removes a Alumni from the list **/
        public void removeAlumnus(Object o)
            alumni.removeElement(o);      
        /** Method searches for Alumni by last name and graduation year **/
        public void searchAlumnus(String lastNameIn, int years)
          // Code will go here eventually  
        }

    And probably you want a list of Alumni not a vector of Objects. So try this:
    import java.util.List;
    import java.util.ArrayList;
    public class AlumniDirectory{
        private final String faculty;
        private final List<Alumnus> alumni = new ArrayList<Alumnus>();
        /** Constructor reads faculty Name and inits new vector **/
        public AlumniDirectory(String facultyIn)
            faculty = facultyIn;      
        /** Method adds a new Alumni to the list **/
        public void addAlumnus(Alumnus alumnus)
            alumni.add(alumnus));
        /** Method removes a Alumni from the list **/
        public void removeAlumnus(Alumnus alumnus)
            alumni.remove(alumnus);      
        /** Method searches for Alumni by last name and graduation year **/
        public void searchAlumnus(String lastNameIn, int years)
          // Code will go here eventually  
        }-Puce
    Edited by: Puce on Oct 23, 2007 7:43 PM
    Edited by: Puce on Oct 23, 2007 7:46 PM

  • How the best way to use the defringe tool in removing chromatic aberration?

    I am having a problem with LR 4.2 in correcting chromatic aberation.  When I try to use the "defringe tool" I receive the following error message, "Cannot set the purple or green fringe color.  Please sample a representative fringe color agian."  However, I can see the sampled pixel in the pallette and read the RGB values.  What am I doing wrong?

    In this case, where the dropper doesn't work, you might have to slide the color selectors left or right to visually select the desired color. So, if for example, you have a blue fringe, you could slide the color selectors to the left so instead of surrounding purple, they now surround more blue-ish colors. Sometimes when you do this however, some areas are "corrected" from blue to something else that should NOT be  corrected. So, you have to "protect" the areas that shouldn't be corrected. This blog post explains it all: http://blogs.adobe.com/lightroomjournal/2012/04/new-color-fringe-correction-controls.html

  • HT1040 Is iPhoto the only way to use the Apple print service?

    I have an iPad and would like to use the Apple print service.  Is the iPhoto app the way to do this?  Thanks.

    The answer to IOS questions would be the better ask in the iPhoto for IOS forum.
    LN

  • TS3376 is the only way to use the find my iphone app to use another iphone or can i do it from my laptop

    i have misplaced my ipod touch and it has the find my iphone app on it can i find it from my laptop or do i have to use another apple product to find it..if not how do i do it..

    Beth_gruetzner wrote:
    If I sign in to my iCloud account on someone else's PC in order to use the Find My iPhone app for my iPhone, then will my phone or email be notified that I signed into iCloud
    Yes.

  • What is the proper way to fix the Flash Plug-in issue that causes Firefox to hang when playing Flash videos

    This is annoying and causing me to set my default to Chrome. Firefox hangs when playing Flash. I have tirelessly tried everything I could. Uninstalling Flash via the Adobe download. Uninstalling FF and every single one of it's folders. I've done it all, multiple times....and continue to have the exact same problem, any Flash video hangs. Please help, I have read countless articles about others having this same problem, yet nobody offers a real solution.
    == URL of affected sites ==
    http://www.youtube.com

    This is annoying and causing me to set my default to Chrome. Firefox hangs when playing Flash. I have tirelessly tried everything I could. Uninstalling Flash via the Adobe download. Uninstalling FF and every single one of it's folders. I've done it all, multiple times....and continue to have the exact same problem, any Flash video hangs. Please help, I have read countless articles about others having this same problem, yet nobody offers a real solution.
    == URL of affected sites ==
    http://www.youtube.com

  • What is the proper way to charge battery in 2012 15 inch macbook pro.

    what is the proper way to charge the battery and make it last longest

    About Batteries in Modern Apple Laptops
    Battery University
    Apple - Batteries - Notebooks
    Apple - Batteries
    Extending the Life of Your Laptop Battery
    MacBook and MacBook Pro- Mac reduces processor speed when battery is removed while operating from an A-C adaptor
    Apple Portables- Calibrating your computer's battery for best performance
    Mac notebooks- Determining battery cycle count

  • What is the proper way to apply SCCM 2012 R2 Cumulative Updates

    Hello All!
    I am looking for a little advice. Since deploying SCCM 2012 R2 I have not yet installed any of the cumulative updates. What is the proper way to install the previusely released updates? I believe there has been 3 CU relases since SCCM 2012R2. Should
    I just install the most recent CU or install all of them starting with CU1? I know each one addresses different issues so I would think install all of them would make sense.
    Thanks,
    Phillip
    Phil Balderos

    No, they're cumulative, so you only have to install the latest.
    My Blog: http://www.petervanderwoude.nl/
    Follow me on twitter: pvanderwoude

  • What is the best way to use recovery files

    I am working in FM 11 and have crashed FM a few times. What is the best way to use the recovery files and save them as the normal file? Then should I filter an explorer window for "recovery" so FM won't keep asking me if I want to use older recovery files? Thanks for your help.

    > What is the best way to use the recovery files ...
    Use a .recover file to extract only the new/changed content that would otherwise be lost if you were instead to open the .auto (if any), or .backup files.
    > ... and save them as the normal file?
    Don't. If the document crashed because of an internal data structure problem, the .recover file (although actually a MIF) is apt to contain that problem.
    Before doing anything, preserve the debris. Copy the .backup and .auto files in particular, because as soon as you open the main .fm file, it's going to overwrite that .backup, and then the .auto at the next auto-save interval. You can dispose of any zero-length files or files with temporary names (which result from the crash itself crashing).
    I typically:
    preserve a snapshot of the debris
    open the original file, and if it won't, the .backup
    open the .recover, .auto or .backup (whichever seems the most useful candidate as a sourcing file)
    copy in the changes from the .recover, .auto or .backup to the working copy
    save the working copy as the original.fm, close the sourcing file
    do a MIF wash on the new original.fm
    clean up the debris in preparation for the next crash

Maybe you are looking for

  • How to add a character at the end of an array element that meets certain criteria.

    Hi. I am using CF 9.2.1. I started learning CF yesterday, and I am trying to figure out a way to add a special character (like "?", "!"," & ") to an array row if the first row element (say, element [1][1]) has a specific letter like " t" in the word

  • Performance degradation on multi-processor computer

    I saw couple similar topics but they are not the same. The issue is that .NET app is not so affected and Java app. See below. Thank you. There is strange picture is observed here. The same test, the same data - the more CPUs computer has, the slower

  • Spotlight can't be trusted? Cant find in ~/Music...

    Hey everyone, Tried to do a quick search in the Finder for a folder in my iTunes Music folder. I was looking to see if I had an artist's album without opening up iTunes (which is still pretty slow). Anyway, neither the Spotlight menu search nor a Fin

  • Administrative rights to Windows Server

    I know that we need administrative rights to a window box during installation and configuration. After cutover to production, is it possible for the DBA to survive if administrative rights are revoked? What daily/often-run tasks will be affected? Tha

  • Error 1002 on my 3GS 16gb

    After using Navigon, my iphone 3 GS crasht. Only able  to call : emergency. Must connected on my PC in iTunes, had to restore, I did but had error 1002.....10 times tried, no succes....no yailbreaking !  What can I do ??  Throwing away ???? ;(  Help!