FileWriter writes always in a new line - java

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();
}

Related

How do i Edit records in a .txt file in Java?

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 need help reading a text file to print to the console

I having trouble figuring this out it supposed to print the contents of the txt file but i cant get it print.
This is the output im supposed to get.
Ingredient __________Amount Needed ______ Amount In Stock
baking soda_________4.50 ________________4.00
sugar ______________6.50________________3.20
import java.util.Scanner;
import java.lang.*;
import java.io.FileReader;
import java.io.IOException;
import java.io.*;
public class Lab8b {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.print("Enter file name : ");
String filename = scan.nextLine();
Scanner fileScan = new Scanner(new File(filename));
while (fileScan.hasNext()) {
String name = fileScan.nextLine();
String ingredientName = fileScan.nextLine();
double amountNeeded = Double.parseDouble(fileScan.nextLine());
double amountInStock = Double.parseDouble(fileScan.nextLine());
if (amountNeeded > amountInStock) {
System.out.printf("Ingredient \t Amount Needed \t Amount in Stock");
System.out.println();
System.out.printf("%10s", ingredientName);
System.out.printf("%8.2f", amountNeeded);
System.out.printf("%16.2f", amountInStock);
} //end if
if (amountNeeded <= amountInStock) {
System.out.println("Nothing");
} //end while
} //end if
} //end main
} //end class
Here are the problems I found with your code:
You created a while loop to read the contents of the file, but you don't do anything with it.
Need to wrap the code in a try-catch since FileNotFoundException might be thrown.
You attempt to call readLine() from filename instead of fileScan
I've assumed that you need amountNeeded and amountInStock to be doubles even though you don't do any calculations with them. If this isn't the case, you can simply leave them as strings instead of parsing.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter file name : ");
String filename = scan.nextLine();
scan.close();
Scanner fileScan = null;
try {
fileScan = new Scanner(new File(filename));
while (fileScan.hasNext()) {
String ingredientName = fileScan.nextLine();
double amountNeeded = Double.parseDouble(fileScan.nextLine());
double amountInStock = Double.parseDouble(fileScan.nextLine());
System.out.printf("Ingredient \t Amount Needed \t Amount in Stock\n");
System.out.printf("%10s", ingredientName);
System.out.printf("%8.2f", amountNeeded);
System.out.printf("%16.2f", amountInStock);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

Writing to a file with printwriter

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);

Reading string from a text file and splitting it into separate array lists and comparing

I'm new to programming in Java and am having some problems solving a problem using array lists and comparisons. The code below is not the attempted full problem but the problem is this:
Essentially read a text file that has a phone number and a double value beside it. 999-878-2233 37.23 then the next line would be 999-889-4664 20.33. Then if a user would type in a value over 25, it should print the first line. Also, I can only loop up to 10 lines.
What I have so far is this.
public static void main(String[] args) throws IOException
{
Scanner input = new Scanner (System.in);
System.out.print ("Enter the filename: ");
String fileName = input.nextLine();
File file = new File(fileName);
Scanner inputFile = new Scanner (file);
String line;
BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName));
int i = 0;
ArrayList<String> list = new ArrayList<String>();
while(((line = bufferedReader.readLine()) != null) && i < 10)
{
System.out.println(line);
i++;
list.add(line);
}
String[] lineList = list.toArray(new String[0]);
System.out.println (Arrays.toString(lineList));
}
}
I know the split option with line.split(" ")) is probably the best way forward. I assume the double value would be put into a separate array list and then compared to the user input and the phone number beside it. The phone number would remain a string and would be printed with it.
I appreciate the help if someone is willing.
================================================
I solved the problem using a different solution.
import java.util.*;
import java.io.*;
import java.text.DecimalFormat;
import java.util.regex.*;
public class labFinalA2
{
public static void main(String[] args) throws IOException
{
Scanner input = new Scanner (System.in);
int i = 0;
double threshold;
System.out.print ("Enter the filename: ");
String fileName = input.nextLine();
File file = new File(fileName);
Scanner inputFile = new Scanner (file);
String line;
BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName));
System.out.print ("Cell bill threshold: ");
threshold = input.nextDouble();
System.out.println ("All cell phones bills at or above the threshold amount.");
System.out.println (" Number Amount");
while(((line = bufferedReader.readLine()) != null) && i < 20)
{
i++;
String str = line;
Pattern p = Pattern.compile("(\\d+(?:\\.\\d+))");
Matcher m = p.matcher(str);
while(m.find())
{
double d = Double.parseDouble(m.group());
if (d >= threshold)
{
String cellBill = Double.toString(d);
String phone = line.replaceFirst(Pattern.quote(cellBill), "");
System.out.println(phone + " "+ d);
}
else
{
inputFile.close();
}
}
}
}
}

Passing Strings in methods

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);

Categories