Hi I'm a beginner to file I/O and I'm having a small problem with writing to a file. What my program should do is write a username and password to a file. Here's my code (ill describe my problem after the code because its specific to program):
public class Helper {
public static void main(String[] args) throws Exception {
Home();
UserInput();
}
private static void Home() throws FileNotFoundException{
System.out.println("Here are the instrucions for the chat program:");
System.out.println("Type *R for registration" );
}
private static void UserInput() throws Exception{
Scanner scan = new Scanner(System.in);
String input = scan.next();
if(input.equals("*R")){
Register();
}
main(new String[0]);
}
private static void Register() throws FileNotFoundException{
try{
File info = new File("info.txt");
info.createNewFile();
FileOutputStream outputStream = new FileOutputStream(info);
PrintWriter out = new PrintWriter(outputStream);
Scanner scan = new Scanner(System.in);
System.out.println("Enter a username: ");
String username = scan.nextLine();
System.out.println("Enter a password: ");
String password = scan.nextLine();
out.println(username + " " + password);
out.flush();
}catch(IOException e){
e.printStackTrace();
}
}
What I need is my info.txt file to store all of the usernames and passwords each pair on a different line, however it only stores the most recent one. That is, each time I write to info.txt it overwrites the most recent pair(username and password). Is there a way around this?
Java FileWriter constructor is called like this:
new FileWriter(String s, boolean append);
This simple constructor indicates that you want to write to the file in append mode.
Try following code:
private static void Register() throws FileNotFoundException{
try{
FileWriter fw = new FileWriter("info.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw);
Scanner scan = new Scanner(System.in);
System.out.println("Enter a username: ");
String username = scan.nextLine();
System.out.println("Enter a password: ");
String password = scan.nextLine();
out.println(username + " " + password);
out.flush();
}catch(IOException e){
e.printStackTrace();
}
}
Use this constructor instead. new FileOutputStream(info,true);
Related
I'm using NetBeans 16 and I'm trying to add the ability to edit a record from a text file I have saved separated by commas.
Ive tried this code here and I don't seem to get any errors (except the one produced as a result of the try catch) but I have no idea why this doesn't seem to work when I try to overwrite a record which I have selected ive tried everything I can think of I'm pretty new to coding so forgive me if there's some obvious error but I have no idea why this doesn't work my text file has 5 entries in a row if that helps but yeah any help is greatly appreciated
public class EditRecords {
private static Scanner x;
public static void main(String[]args)
{
String filepath = "VehicleInforUpd.txt";
System.out.println("Enter Registration of Entry You Wish To Edit");
Scanner scanner = new Scanner(System.in);
String editTerm = scanner.nextLine();
System.out.println("Enter new Registration: ");
String newReg = scanner.nextLine();
System.out.println("Enter new Make: ");
String newMake = scanner.nextLine();
System.out.println("Enter New Model: ");
String newModel = scanner.nextLine();
System.out.println("Enter New Year: ");
String newYear = scanner.nextLine();
System.out.println("Enter New Comments: ");
String newComment = scanner.nextLine();
editRecord(filepath,editTerm,newReg,newMake,newModel,newYear,newComment);
}
public static void editRecord(String filepath,String editTerm,String newReg,String newMake,String newModel, String newYear, String newComment)
{
String tempFile = "temp.txt";
File oldFile = new File(filepath);
File newFile = new File(tempFile);
String reg = ""; String make = ""; String model = ""; String year = ""; String comment = "";
try
{
FileWriter fw = new FileWriter(tempFile,true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
while(x.hasNext())
{
reg = x.next();
make = x.next();
model = x.next();
year = x.next();
comment = x.next();
if(reg.equals(editTerm))
{
pw.println(newReg+","+newMake+","+newModel+","+ newYear+","+newComment);
}
else
{
pw.println(reg+","+make+","+model+","+year+","+comment);
}
}
x.close();
pw.flush();
pw.close();
oldFile.delete();
File dump = new File(filepath);
newFile.renameTo(dump);
JOptionPane.showMessageDialog(null, "Changes Succesfully Saved");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
The Print stack trace results but im not sure what would cause the NullPointerException im getting
java.lang.NullPointerException
at com.mycompany.anprsystems.EditRecords.editRecord(EditRecords.java:70)
at com.mycompany.anprsystems.EditRecords.main(EditRecords.java:52)
I am trying to prompt the user to enter a file name and search for the filename and save it to 2 2-D array.
Example of the file is:
BBBBB
BBBBB
BBBBB
BBBBB
public class maze_2D{
static Scanner s = new Scanner(System.in);
public static void FromFile() throws Exception{//
System.out.println("Enter File name");
String file = s.nextLine();
File f = new java.io.File(file);
Scanner scanner = new Scanner(f);
// Read from file.....
But when I run the program, i get an error
Enter Filename
java.io.FileNotFoundException:
Why is this happening, why this scanner doesn't allow me to enter any file name?
While inputting file name in command prompt give the full path including file name with extension where your file resides in the File System.
System.out.println("Enter File name");
String file = s.nextLine();
File f = new java.io.File(file);
try {
Scanner sc = new Scanner(f);
while (sc.hasNextLine()) {
int i = sc.nextInt();
System.out.println(i);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
I made a little class using most of your code ad it worked fine... try examining your path+filename to ensure it is really there.
I have heard of scanner.getInteger forcing you to add a scanner.nextLine() after it but you are using nextLine to the the fileName so this shouldn't be the case.
public class NewClass {
static Scanner s = new Scanner(System.in);
public static void main(String args[]) throws Exception {
FromFile();
}
public static void FromFile() throws Exception {
System.out.println("Enter File name");
// I enter '/Users/myMame/Downloads/testFile.txt'
String file = s.nextLine();
File f = new java.io.File(file);
Scanner scanner = new Scanner(f);
// do your 2D array manipulation
while(scanner.hasNextLine()){
String line = scanner.nextLine();
System.out.println("line: " + line);
}
}
}
I'm trying to get the user to input their file name. If the file name is valid it passes through. However, if the file name is invalid then its suppose to ask the user again for a file. If a purposely enter an invalid file name, the program doesn't get past the exception branch.
Here's the code:
public class LineNumbers {
private static Scanner getFile() {
Scanner in = new Scanner(System.in);
Scanner scannedFile = new Scanner(System.in);
String inputFile;
boolean validFile = false;
while (!validFile) {
try {
System.out.print("Enter your file name: ");
inputFile = in.nextLine();
scannedFile = new Scanner(new FileReader(inputFile));
validFile = true;
} catch (Exception e) {
System.out.print(e);
System.out.print("Invalid File");
in.next();
scannedFile.next();
}
}
return scannedFile;
}
public static void main(String[] args) {
String word = getFile().nextLine();
}
}
Do are getting problems when calling in.next(); and scannedFile.next(); in catch block. You have already expected in.readLine() if invalid user input occurred. Additionally you should understand that the scannedFile is reachable, that's why got the exception. So you cannot use scannedFile.next(); in the catch block also.
Do following modifications
private static Scanner getFile() {
Scanner in = new Scanner(System.in);
Scanner scannedFile = new Scanner(System.in);
String inputFile;
boolean validFile = false;
while (!validFile) {
try {
System.out.print("Enter your file name: ");
inputFile = in.nextLine();
scannedFile = new Scanner(new FileReader(inputFile));
validFile = true;
} catch (Exception e) {
System.out.println(e);
System.out.println("Invalid File");
//no scanned file, input file could not find
scannedFile = null;
//file was not valid
validFile = false;
}
}
return scannedFile;
}
im having a big problem: I'm trying to write a word or phrase but when my program recieves the phrase, it writes in the file one word per line...
import java.io.*;
import java.util.Scanner;
public class Hola{
public static void main(String[] args) throws IOException{
FileWriter fw = new FileWriter("Pru2.java");
BufferedWriter bw = new BufferedWriter(fw);
Scanner sc = new Scanner(System.in);
String palabra = sc.next();
while(palabra.compareTo("z")!=0){
bw.write(palabra);
bw.newLine();
bw.flush();
palabra = sc.next();
}
bw.close();
}
}
When i write this phrase in the cmd ("This is an example")and then I open the file, this is what i read:
This
is
an
example
I will really appreciate any help!
Thank you very much.
Hope the below code helps
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("Pru2.txt");
BufferedWriter bw = new BufferedWriter(fw);
Scanner sc = new Scanner(System.in);
String palabra = sc.next();
while (palabra.compareTo("z") != 0) {
bw.write(palabra);
bw.write(" "); //add this line to have space
//bw.newLine();//comment this line
palabra = sc.next();
}
bw.flush();
bw.close();
}
I can't figure out how to pass the Strings need to the method below.
stringToFile(); and
readingStringFromFile();
I know I need to pass the Strings in the main method but I can't figure out how.
Thanks in advance.
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);//allow for use of keyboard input
mask(keyboard);
printingString();
fileName(keyboard);
stringToFile();
readingStringFromFile();
}
public static int mask(Scanner keyboard){
int holder;//creats a temp int
System.out.print("Enter the encryption mask: ");//asks fro encrytipon
holder = keyboard.nextInt();//userinput to holder
keyboard.nextLine();//consumption
return holder;//returns encryption mask
}
public static void fileName(Scanner keyboard){
String fileName ="a";
System.out.print("\nEnter a file name without extensions: ");
fileName = keyboard.next();//userinput to fileName
String completeFileName = fileName + ".txt";
}
public static void printingString(){
System.out.println("Original random character string:");
for (int i = 0; i < 50; i++)//loop to obtain 50 random characters
{
char randomChar = (char) ((Math.random()*255)+32);
System.out.print((randomChar));
}
}
public static void stringToFile(String completeFileName, String printingString)
throws FileNotFoundException {
System.out.println("Saving Original random character string...");
File myFile = new File (completeFileName);
Scanner fileReader = new Scanner (myFile);
PrintWriter fileWriter = new PrintWriter (myFile);
fileWriter.println(printingString);
fileWriter.close();
}
public static void readingStringFromFile(String completeFileName)
throws FileNotFoundException {
System.out.println("Original random character string from the file");
File myFile = new File (completeFileName);
Scanner fileReader = new Scanner (myFile);
String lineFromFile = fileReader.nextLine();
System.out.println(lineFromFile);
}
In your main method you should get the input -
System.out.println("Enter file name : ");
String completeFileName = keyboard.next();
System.out.println("Enter string : ");
String printingString = keyboard.next();
stringToFile(completeFileName, printingString);