简体   繁体   中英

Java I/O: How to Print Loop Outputs to one file?

I'm trying to write and save multiple contacts into one file and then store it as a Hex file, but it keeps creating multiple files (one per contact). I tried to move the:

  System.out.print("Type a name for this file, followed by hitting 'enter': ");
    String fName = kbReader.nextLine();

    //append information to the string to be converted
    utfString = name + "\r\n" + pNumber + "\r\n" + fact;

    //outputs variables to file in hexadecimal format
    PrintStream fileStream = new PrintStream(fName);
    fileStream.println(toHex(utfString));

section to the While loop, which would create the file after the user says they have no more contacts to add to the file. The path I want to take with this code is that each contact is written to the file as Hex code and then the user says they want to input another contact, so the program writes the new contact to the file in Hex code right after the first one.

Code:

 import java.util.Scanner;
 import java.io.PrintStream;
 import java.io.IOException;

public class Exercise27{

public static String toHex(String currString){

    //converts a string to a byte-array
    byte[] preConvert = currString.getBytes();

    //converts byte-array to hexadecimal string using a function from the javax library included in Java Platform SE 7 and onwards
    return javax.xml.bind.DatatypeConverter.printHexBinary(preConvert);

}

public static void main(String[] args) throws IOException{

    //starts keyboard input
    Scanner kbReader = new Scanner(System.in);
    Boolean MoreContacts = true;
    String More;
    do{

    //declare variable to convert to hex later on
    String utfString = "";

    //create variables for user-information
    System.out.print("Type your full name, followed by hitting 'enter': ");
    String name = kbReader.nextLine();
    System.out.print("Type your phone number, followed by hitting 'enter': ");
    String pNumber = kbReader.nextLine();
    System.out.print("Type one interesting fact about yourself, followed by hitting 'enter': ");
    String fact = kbReader.nextLine();
    System.out.print("Type a name for this file, followed by hitting 'enter': ");
    String fName = kbReader.nextLine();

    //append information to the string to be converted
    utfString = name + "\r\n" + pNumber + "\r\n" + fact;

    //outputs variables to file in hexadecimal format
    PrintStream fileStream = new PrintStream(fName);
    fileStream.println(toHex(utfString));

    System.out.println("More contacts? (Enter y or n)");
    MoreContacts = false;
    More = kbReader.nextLine();
    System.out.println("More: " + More);
    if((More.equalsIgnoreCase("y")) || (More.equalsIgnoreCase("yes")))
    {
      MoreContacts = true; 
    }

    }while(MoreContacts);



    PrintStream fileStream;

    //close your systems
    //fileStream.close();
    kbReader.close();

}

}

If you are wanting to use the same file for the contacts then you really should only ask for the filename once. Probably in this case, before the while loop.

So move the lines before the loop:

System.out.print("Type a name for this file, followed by hitting 'enter': ");
String fName = kbReader.nextLine();

I then suggest you use a FileWriter and then you can choose to append to the file.

File yourFile = new File(fName);
FileWriter fw = new FileWriter(yourFile, true);

Then in your loop you can write to this using

fw.write(toHex(utfString));

but this wont include a newlinw so you might need to also add

fw.write("\r\n");

Then don't forget to close the writer after writing all data to it

fw.close();

The problem is PrintStream is created inside the loop that causes the file to be truncated as mentioned in the PrintStream constructor javadoc:

Parameters:

file - The file to use as the destination of this print stream. If the file exists, then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.

You can try it as:

import java.util.Scanner;
import java.io.PrintStream;
import java.io.IOException;

public class Exercise27{

public static String toHex(String currString){

//converts a string to a byte-array
byte[] preConvert = currString.getBytes();

//converts byte-array to hexadecimal string using a function from the javax library included in Java Platform SE 7 and onwards
return javax.xml.bind.DatatypeConverter.printHexBinary(preConvert);

}

public static void main(String[] args) throws IOException{

//starts keyboard input
Scanner kbReader = new Scanner(System.in);
System.out.print("Type a name for this file, followed by hitting 'enter': ");
String fName = kbReader.nextLine();
PrintStream fileStream = new PrintStream(fName);
Boolean MoreContacts = true;
String More;
do{

//declare variable to convert to hex later on
String utfString = "";

//create variables for user-information
System.out.print("Type your full name, followed by hitting 'enter': ");
String name = kbReader.nextLine();
System.out.print("Type your phone number, followed by hitting 'enter': ");
String pNumber = kbReader.nextLine();
System.out.print("Type one interesting fact about yourself, followed by hitting 'enter': ");
String fact = kbReader.nextLine();


//append information to the string to be converted
utfString = name + "\r\n" + pNumber + "\r\n" + fact;

//outputs variables to file in hexadecimal 
fileStream.println(toHex(utfString));

System.out.println("More contacts? (Enter y or n)");
MoreContacts = false;
More = kbReader.nextLine();
System.out.println("More: " + More);
if((More.equalsIgnoreCase("y")) || (More.equalsIgnoreCase("yes")))
{
  MoreContacts = true; 
}

}while(MoreContacts);



PrintStream fileStream;

//close your systems
//fileStream.close();
kbReader.close();

}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM