Skip to content

Instantly share code, notes, and snippets.

@memish
Created November 29, 2018 02:43
Show Gist options
  • Save memish/9a4e71d0189141ccd38b959f5f0e7e29 to your computer and use it in GitHub Desktop.
Save memish/9a4e71d0189141ccd38b959f5f0e7e29 to your computer and use it in GitHub Desktop.
import java.util.*;
import java.io.*;
//import java.text.*;
public class WriteToFile {
String cont="yes"; //allows while loop to run through at
// least once - could of done a do-while instead
boolean append = false;
public WriteToFile(){
Scanner input = new Scanner(System.in);
String x = "1";
while(x.equals("1")){
System.out.println("Please enter your full name " );
String fullName = input.nextLine();
System.out.println("Please enter your gradYear " );
String gradyear = input.nextLine();
System.out.println("Press one to continue " );
x = input.nextLine();
printToFile("names.txt",fullName,gradyear);
}
}
public void printToFile(String fileName, String var1, String var2){
File f = new File(fileName); //creates variable f of type FILE -
//need this to create the file or append the file
try{
PrintWriter pw = null; //creates variable pw of type PrinterWriter - need this to write to file
//BELOW IS TEST TO SEE IF FILE EXIST AND IF IT DOES NOT WE CREATE THE FILE
if ( f.exists() ) {
append = true; //file exist and this gives the user permission to append to the file
pw = new PrintWriter(new FileWriter(new File(fileName), append));
//this attaches PrinterWriter to the file and allows user to append
}else {
append = false; //won't be appending to the file - creating a new file
pw = new PrintWriter(new FileWriter(new File(fileName))); //creates the new file
}
//ABOVE IS TEST TO SEE IF FILE EXIST AND IF IT DOES NOT WE CREATE THE FILE
boolean autoFlush = false; //keeps the file in memory
pw.println (var1 +"," + var2); //prints one line of data to the file
// The data includes four variables separated by commas
pw.close();//closes the file
}catch (Exception e){ //if there was an error this would catch it and printer message below to the screen
System.out.println("There was an error");
}
}//end of printToFile Method
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment