Using 2 methods in one to read and write to file - java

I have written 2 methods - A write to method and a read from method. They work fine but I want to combine them so that they work like the pseudo code that I have written:
prompt user for input filename
open input file
prompt user for output filename
open output file
while there are lines in the input file
read a line
print it to screen
writeit to the output file
close the input file
close the output file
I have tried a few different variations but I can't seem to get this to work?
Read to method:
public void readFile() {
FileReader fileReader = null;
BufferedReader bufferedReader = null;
String InputFileName;
String nextLine;
clrscr();
System.out.println("Please enter the name of the file that is to be READ (e.g. aFile.txt: ");
InputFileName = Genio.getString();
try {
fileReader = new FileReader(InputFileName);
bufferedReader = new BufferedReader(fileReader);
nextLine = bufferedReader.readLine();
while (nextLine != null) {
System.out.println(nextLine);
nextLine = bufferedReader.readLine();
}
} catch (IOException e) {
System.out.println("Sorry, there has been a problem opening or reading from the file");
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
System.out.println("An error occurred when attempting to close the file"); }
}
}
}
Write to method:
public void writeFile() {
String myString;
clrscr();
System.out.println("Begin typing the contents to you wish to WRITE to file: ");
myString = Genio.getString();
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
FileOutputStream outputStream = null;
PrintWriter printWriter = null;
try {
outputStream = new FileOutputStream("writing.txt");
printWriter = new PrintWriter(outputStream);
printWriter.write(myString);
printWriter.println("\n");
// write information to the file via the PrintWriter
while (!myString.equals("")) {
myString = Genio.getString();
printWriter.print(myString + "\n");
}
System.out.println("File: 'writing.txt' has been saved with the contents above.\n\nYou can now open this file using the other options in the menu screen.");
pressKey();
} catch (IOException e) {
System.out.println("Sorry, there has been a problem opening or writing to the file");
} finally {
if (printWriter != null)
printWriter.close();
}
}
The Genio class that deals with user input:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Genio {
public Genio() {}
private static String getStr() {
String inputLine = "";
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
try {
inputLine = reader.readLine();
} catch(Exception exc) {
System.out.println ("There was an error during reading: "
+ exc.getMessage());
}
return inputLine;
}
public static int getInteger() {
int temp=0;
boolean OK = false;
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
do {
try {
temp = Integer.parseInt(keyboard.readLine());
OK = true;
} catch (Exception eRef) {
if (eRef instanceof NumberFormatException)
System.out.print("Integer value needed: ");
else
System.out.println("Please report this error: "+eRef.toString());
}
} while(OK == false);
return(temp);
}
public static float getFloat() {
float temp=0;
boolean OK = false;
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
do {
try {
temp = Float.parseFloat(keyboard.readLine());
OK = true;
} catch (Exception eRef) {
if (eRef instanceof NumberFormatException)
System.out.print("Number needed: ");
else
System.out.println("Please report this error: "+eRef.toString());
}
} while(OK == false);
return(temp);
}
public static double getDouble() {
double temp=0;
boolean OK = false;
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
do {
try {
temp = Double.parseDouble(keyboard.readLine());
OK = true;
} catch (Exception eRef) {
if (eRef instanceof NumberFormatException)
System.out.print("Number needed: ");
else
System.out.println("Please report this error: "+eRef.toString());
}
} while(OK == false);
return(temp);
}
public static char getCharacter() {
String tempStr="";
char temp=' ';
boolean OK = false;
do {
try {
tempStr = getStr();
temp = tempStr.charAt(0);
OK = true;
} catch (Exception eRef) {
if (eRef instanceof StringIndexOutOfBoundsException) {
// means nothing was entered so prompt ...
System.out.print("Enter a character: ");
} else
System.out.println("Please report this error: "+eRef.toString());
}
} while(OK == false);
return(temp);
}
public static String getString() {
String temp="";
try {
temp = getStr();
} catch (Exception eRef) {
System.out.println("Please report this error: "+eRef.toString());
}
return(temp);
}
}

Here is your merged function readAndWrite():
public static void readAndWrite() {
FileReader fileReader = null;
BufferedReader bufferedReader = null;
FileOutputStream outputStream = null;
PrintWriter printWriter = null;
String InputFileName, OutputFileName;
String nextLine;
clrscr();
// Prompt user for input filename
System.out.println("Please enter the name of the file that is to be READ (e.g. aFile.txt: ");
InputFileName = Genio.getString();
// Prompt user for output filename
System.out.println("Please enter the name of the file that is to be WRITTEN (e.g. bFile.txt: ");
OutputFileName = Genio.getString();
try {
// Open input file
fileReader = new FileReader(InputFileName);
bufferedReader = new BufferedReader(fileReader);
// Open output file
outputStream = new FileOutputStream(OutputFileName);
printWriter = new PrintWriter(outputStream);
// Read a line
nextLine = bufferedReader.readLine();
// While there are lines in the input file
while (nextLine != null) {
// Print it to screen
System.out.println(nextLine);
// Write it to the output file + a new-line
printWriter.write(nextLine+"\n");
// Read a line
nextLine = bufferedReader.readLine();
}
// Close the input file
bufferedReader.close();
// Close the output file
printWriter.close();
} catch (IOException e) {
System.out.println("Sorry, there has been a problem opening or reading from the file");
e.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
System.out.println("An error occurred when attempting to close the file");
}
}
if(printWriter != null) {
printWriter.close();
}
}
}
Let me know whether it works or not
Happy coding :) -Charlie

Related

File copier is printing out my whole excerpt, I want it to do it line by line with user input between

I need my program to print this file line by line, waiting for the user to press enter between each one. My code keeps printing the whole excerpt. What do I need to change?
import java.io.*;
import java.util.*;
public class NoteCopier {
public static void main(String[] args) throws IOException {
System.out.println("Hello! I copy an excerpt to the screen line for line"
+ " just press enter when you want a new line!");
try {
File file = new File("excerpt.txt");
FileInputStream fis = new FileInputStream(file);
InputStreamReader inreader = new InputStreamReader(fis);
BufferedReader reader = new BufferedReader(inreader);
String line = reader.readLine();
Scanner scan = new Scanner(System.in);
while(true) {
String scanString = scan.nextLine();
if(line != null) {
if(scanString.isEmpty()){
System.out.println(line);
line = reader.readLine();
}
else {
scanString = null;
break;
}
}
}
}
catch(IOException e) {
e.printStackTrace();
}
}
}
If line is null you'll loop forever; the nested if statements.
I did it in the new Stream style, without the ubiquitous but needless Scanner on System.in.
private void dump(String file) {
Path path = Paths.get(file);
BufferedReader con = new BufferedReader(new InputStreamReader(System.in));
try (Stream<String> in = Files.lines(path, Charset.defaultCharset())) {
AtomicInteger lineCounter = new AtomicInteger();
in.forEach(line -> {
System.out.println(line);
if (lineCounter.get() == 0) {
String input = null;
try {
input = con.readLine();
} catch (IOException e) {
}
if (input == null) {
throw new IndexOutOfBoundsException();
} else if (input.equals(" ")) {
lineCounter.set(10);
}
} else {
lineCounter.decrementAndGet();
}
});
} catch (IndexOutOfBoundsException e) {
System.out.println("< Stopped.");
} catch (IOException e) {
e.printStackTrace();
}
}
With CtrlD you can exit on Windows I believe.
I have added that a line with a Space will dump the next 10 lines.
The ugly thing are the user input lines.
With java.io.Console one can ask input with a String prompt, which then can be used to print the file's line as prompt.
private void dump(String file) {
Path path = Paths.get(file);
Console con = System.console();
try (Stream<String> in = Files.lines(path, Charset.defaultCharset())) {
AtomicInteger lineCounter = new AtomicInteger();
in.forEach(line -> {
if (lineCounter.get() == 0) {
//String input = con.readLine("%s |", line);
String input = new String(con.readPassword("%s", line));
if (input == null) {
throw new IndexOutOfBoundsException();
} else if (input.equals(" ")) {
lineCounter.set(10);
}
} else {
System.out.println(line);
lineCounter.decrementAndGet();
}
});
} catch (IndexOutOfBoundsException e) {
System.out.println("< Stopped.");
} catch (IOException e) {
e.printStackTrace();
}
}
Using a prompt with the file's line, and asking a non-echoed "password" will be sufficient okay. You still need the Enter.
There is one problem: you must run this as real command line. The "console" in the IDE uses System.setIn which will cause a null Console. I simply create a .bat/.sh file. Otherwise System.out.print(line); System.out.flush(); might work on some operating system.

String cannot be converted to array

I have a program that reads in a file using a filename specified by the user.
All file contents must be read and stored in the array. I seem to have done the IO Correctly besides this error. I understand what the error is but not sure how to correct.
EDIT: The array is already defined in the file.
Zoo.java:284: error: incompatible types: String cannot be converted to
Animals
animals[ j ] = bufferedReader.readLine();
Here is my code for the readFile Submodule:
public String readFile(Animals[] animals)
{
Scanner sc = new Scanner(System.in);
String nameOfFile, stringLine;
FileInputStream fileStream = null;
BufferedReader bufferedReader;
InputStreamReader reader;
System.out.println("Please enter the filename to be read from.");
nameOfFile = sc.nextLine();
try
{
constructed = true;
fileStream = new FileInputStream(nameOfFile);
bufferedReader = new BufferedReader(new InputStreamReader(fileStream));
while((stringLine = bufferedReader.readLine()) != null)
{
for(int j = 0; j < animals.length; j++)
{
animals[j] = bufferedReader.readLine();
}
}
fileStream.close();
}
catch(IOException e)
{
if(fileStream != null)
{
try
{
fileStream.close();
}
catch(IOException ex2)
{
}
}
System.out.println("Error in file processing: " + e.getMessage();
}
}
Thanks for the help.
animals is array of Animals, but bufferedReader.readLine() reads line. You should convert it to Animal. I don't see definition of your class Animals, but, I think, there should be constructor that takes String as argument.
So, If i'm right, you should basically write:
animals[j] = new Animals(bufferedReader.readLine());
Lots of problems in your code. Starting with the method's input. Also reading from file.
public static void main(String[] args) {
// TODO code application logic here
for(String entry : readFile())
{
System.out.println(entry);
}
}
static public String[] readFile()
{
Scanner sc = new Scanner(System.in);
InputStreamReader reader;
System.out.println("Please enter the filename to be read from.");
String nameOfFile = sc.nextLine();
try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(nameOfFile))); )
{
//constructed = true; why?
String stringLine;
ArrayList<String> arraylist = new ArrayList();
while((stringLine = bufferedReader.readLine()) != null)
{
arraylist.add(stringLine);
}
return arraylist.toArray(new String[0]);
}
catch (FileNotFoundException ex)
{
Logger.getLogger(Filetoarray.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex)
{
Logger.getLogger(Filetoarray.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}

Java Read/Write, Rename File having issue

I was using my code to do a replace line feature. It was working initially but suddenly my new file became blank and the code did not bring me back to the AdminMenu(), as well as the file not being renamed. There is also another issue where if I use "\r\n" there will be a blank line on top of my file which I am trying to remove. I tried using \n after totalChips, but it doesn't seem to work. I could use some advice on this.
output
<Blank File>
expected output
Line1|password|500
Line2|password|600
//ModifiedLine can be either line based on UserName
codes are below
public static void AddChips() {
File oldFileName = new File("players.dat");
File tmpFileName = new File("newplayers.dat");
BufferedReader br = null;
BufferedWriter bw = null;
ArrayList<String> player = new ArrayList<String>();
try {
br = new BufferedReader(new FileReader(oldFileName));
bw = new BufferedWriter(new FileWriter(tmpFileName));
String line;
Scanner read = new Scanner(System.in);
System.out.println("Please Enter Username");
String UserN = read.nextLine();
System.out.println("Please Enter Chips to Add");
String UserCadd = read.nextLine();
while ((line = br.readLine()) != null) {
String[] details = line.split("\\|");
String Username = details[0];
String Password = details[1];
String Chips = details[2];
int totalChips = (Integer.parseInt(UserCadd)+ Integer.parseInt(Chips));
if (Username.equals(UserN))
line = Username + "|" + Password + "|" + totalChips;
bw.write("\r\n"+line);
}
bw.close();
br.close();
oldFileName.delete();
tmpFileName.renameTo(oldFileName);
AdminMenu();
} catch (Exception e) {
e.printStackTrace();
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
new Error
java.lang.ArrayIndexOutOfBoundsException: 1
at testcode.AddChips(testcode.java:53)
at testcode.main(testcode.java:11)

Deleting File and Renaming file in java

i am trying to use this code to replace field and after the replace is done i like to delete the file. But when i replace the file only 1 line was saved. How should i ensure that the other lines will be saved?
public static void main(String[] args){
AddChips();
}
public static void AddChips() {
File oldFile = new File ("players.dat");
File newFile = new File ("tempchips.dat");
BufferedReader br = null;
BufferedWriter bw = null;
ArrayList<String> player = new ArrayList<String>();
try {
br = new BufferedReader(new FileReader(oldFile));
bw = new BufferedWriter(new FileWriter(newFile));
String line;
Scanner read = new Scanner(System.in);
System.out.println("Please Enter Username");
String UserN = read.nextLine();
System.out.println("Please Enter Chips to Add");
String UserCadd = read.nextLine();
while ((line = br.readLine()) != null) {
String[] details = line.split("\\|");
String Username = details[0];
String Password = details[1];
String Chips = details[2];
int totalChips = (Integer.parseInt(UserCadd)+ Integer.parseInt(Chips));
if (Username.equals(UserN)){
line = Username + "|" + Password + "|" + totalChips;
bw.write(line + System.getProperty("line.separator"));
}
//issue is here
br.close();
bw.close();
oldFile.delete();
newFile.renameTo(oldFile);
//AdminMenu();
}
} catch (Exception e) {
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
//
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//
}
}
}

Create method that opens a file, then lets's user write to file then end when pressing enter on empty line?

I want to create a method that which opens a file for writing, then prompts the user to enter lines of text until they press enter on an empty line to stop input.
It's giving some trouble in that I can get the method run and I can input text but it wont close or save? I hit return after my text to go to a blank line and hit return again but it just moves onto another line.
I have written the following but can't get it working correctly.
My code:
public void writeFile()
{
String myString;
clrscr();
System.out.println("Begin typing: ");
myString = Genio.getString();
FileOutputStream outputStream = null;
PrintWriter printWriter = null;
// use a try-catch-finally block to catch file-related exceptions
try
{
outputStream = new FileOutputStream("writing.txt");
printWriter = new PrintWriter(outputStream);
printWriter.write(myString);
printWriter.newLine();
// write information to the file via the PrintWriter
while (myString != "")
{
printWriter.print(myString + " ");
}
}
catch (IOException e)
{
System.out.println("Sorry, there has been a problem opening or writing to the file");
}
finally
{
if (printWriter != null)
{
printWriter.close();
}
}
}
If it's needed, Genio is the class that deals with user input:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Genio
{
public Genio()
{
}
private static String getStr()
{
String inputLine = "";
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
try
{
inputLine = reader.readLine();
}
catch(Exception exc)
{
System.out.println ("There was an error during reading: "
+ exc.getMessage());
}
return inputLine;
}
public static int getInteger()
{
int temp=0;
boolean OK = false;
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
do
{
try
{
temp = Integer.parseInt(keyboard.readLine());
OK = true;
}
catch (Exception eRef)
{
if (eRef instanceof NumberFormatException)
{
System.out.print("Integer value needed: ");
}
else
{
System.out.println("Please report this error: "+eRef.toString());
}
}
} while(OK == false);
return(temp);
}
public static float getFloat()
{
float temp=0;
boolean OK = false;
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
do
{
try
{
temp = Float.parseFloat(keyboard.readLine());
OK = true;
}
catch (Exception eRef)
{
if (eRef instanceof NumberFormatException)
{
System.out.print("Number needed: ");
}
else
{
System.out.println("Please report this error: "+eRef.toString());
}
}
} while(OK == false);
return(temp);
}
public static double getDouble()
{
double temp=0;
boolean OK = false;
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
do
{
try
{
temp = Double.parseDouble(keyboard.readLine());
OK = true;
}
catch (Exception eRef)
{
if (eRef instanceof NumberFormatException)
{
System.out.print("Number needed: ");
}
else
{
System.out.println("Please report this error: "+eRef.toString());
}
}
} while(OK == false);
return(temp);
}
public static char getCharacter()
{
String tempStr="";
char temp=' ';
boolean OK = false;
do
{
try
{
tempStr = getStr();
temp = tempStr.charAt(0);
OK = true;
}
catch (Exception eRef)
{
if (eRef instanceof StringIndexOutOfBoundsException)
{
// means nothing was entered so prompt ...
System.out.print("Enter a character: ");
}
else
{
System.out.println("Please report this error: "+eRef.toString());
}
}
} while(OK == false);
return(temp);
}
public static String getString()
{
String temp="";
try
{
temp = getStr();
}
catch (Exception eRef)
{
System.out.println("Please report this error: "+eRef.toString());
}
return(temp);
}
}
You class works fine for the most part. I fixed the problematic part for you:
// write information to the file via the PrintWriter
while (!myString.equals(""))
{
myString = Genio.getString();
printWriter.print(myString + "\n");
}
First the condition inside the while was incorrect. MyString has to be compared using the equals operator (or using the isEmpty method).
Second, you need to keep reading into myString inside the loop, otherwise you get an infinite loop and it will never exit.
Third, you want want to add newlines to the output file, so I added them.
You only read myString once, before the while loop starts.
You don't compare strings with == or !=
Change
while (myString != "") to while (!myString.equals(""))
You have an infinite loop, because you only read myString before you enter the while loop, so your condition will never be false.
Also, as Rishi Dua said, you can't compare strings with the usual == ou != operators, you have to use either .equals() or .isEmpty.
Comparing == and equals method.
Since java.lang.String class override equals method, It return true if two String object contains same content.
But,
== will only return true if two references are pointing to same object.
Modified code:
while (! myString.equals("")){
// Write your code here
myString = Genio.getString();
printWriter.print(myString + "\n");
}

Categories