import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class backup {
public static void main(String[] args) {
System.out.println("\nThe names in the file are:\n");
readFromFile();
}
public static void readFromFile() {
try {
Scanner file = new Scanner(new File("Names.txt"));
PrintWriter pass = new PrintWriter("pass.txt");
PrintWriter fail = new PrintWriter("fail.txt");
Scanner input = new Scanner(System.in);
while (file.hasNext()) {
String name = file.nextLine();
System.out.printf("Please enter " + name + "'s mark:");
int mark = input.nextInt();
Scanner kybd = new Scanner(System.in);
{
if (mark >= 40) {
// System.out.println(name + " has passed");
pass.println(name);
} else {
// System.out.println(name + " has failed");
fail.println(name);
}
}
} // end while
} // end try
catch (IOException ioe) {
System.out.println("Error handling file");
} // end catch
}// readFromFile
}
Unable to write to the file pass and fail the Names file is just a list of names if the user scores over 40 they go into the pass however i cant get the txt file to populate the output.
When i insert my printwriter in the while it is only the last entry which gets added to either pass or fail txt file.
The PrintWriter only really writes when they are closed (close) or flushed (flush or maybe when it thinks it is time ;-)).
Try to use try-with-resources whenever possible, that way you do not need to think about closing/flushing a stream or writer. try-with-resources takes care that AutoClosable-implementations are closed automatically at the end of the try-block.
Your sample rewritten with try-with-resources (only showing the initial part):
try(
Scanner file = new Scanner(new File("Names.txt"));
PrintWriter pass = new PrintWriter("pass.txt");
PrintWriter fail = new PrintWriter("fail.txt")
) {
The rest can stay as is... or if you like: you may also want to lookup the Files-API. Maybe using Files.lines is something for you?
You should call the function close on your file for it to be written on the dsisk.
Otherwise you modifications are only in memory
Something like: file.close()
If you use PrintWriter, you have to close the stream at the end. Otherwise, it will be only in memory. Try this:
try {
Scanner file = new Scanner(new File("Names.txt"));
PrintWriter pass = new PrintWriter("pass.txt");
PrintWriter fail = new PrintWriter("fail.txt");
Scanner input = new Scanner(System.in);
while (file.hasNext()) {
String name = file.nextLine();
System.out.printf("Please enter " + name + "'s mark:");
int mark = input.nextInt();
//Scanner kybd = new Scanner(System.in);
//{
if (mark >= 40) {
// System.out.println(name + " has passed");
pass.println(name);
} else {
// System.out.println(name + " has failed");
fail.println(name);
}
//}
} // end while
pass.close();
fail.close();
} // end try
catch (IOException ioe) {
System.out.println("Error handling file");
}
You need to make sure that you add a finally block at the end and call the close method on anything that is closeable so in this case on the printwriter. In this case
pass.close() and fail.close().
Related
I'm trying to read integers from a text file, but I want to handle the first line differently from the rest, and take the following lines and loop some calculations. Below is my file reader, my question is about the next part, however this may provide some context.
public class main
{
BufferedReader in;
public main() throws FileNotFoundException
{
System.out.println("please enter the name of the text file you wish you import. Choose either inputs or lotsainputs. Nothing else");
Scanner keyboard = new Scanner(System.in);
String filename = keyboard.nextLine();
File file = new File(filename);
System.out.println("You have loaded file: \t\t"+filename);
in = new BufferedReader(new FileReader(file));
Scanner inputFile = new Scanner(file);
String element1 = inputFile.nextLine().toUpperCase();
try
{
while ((element1 = in.readLine()) != null)
{
System.out.println("Line to process:\t\t"+element1);
myCalculations(element1);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
The first text file look like this:
200 345
36
The second text file look like this:
200 345
36
45
36
21
Here is the method called:
public static void myCalculations(String s)
{
String[] items = s.split(" ");
int[] results = new int[100];
String errorMessage = "that's a wrap!";
for (int i = 0; i < items.length; i++)
{
try {
int stuff = Integer.parseInt(items[i]);
results[i] = stuff;
}
catch (NumberFormatException nfe) {
System.out.println(results);
System.out.println(errorMessage);
}
}
int health = result[0];
int power = result[1];
int days = result[2];
some calculations....
returns new health and power of the car.
same calculations but results[3] as the time period
returns new health and power of car
etc....
}
The method parses the integers, puts them into the results[] array.
Lets say the first two numbers of the text file are health and power of a car. Each proceeding number are days between races. Each race there is deterioration of the of the car and engine, the amount of deterioration is a factor of days in between each race.
I have used results[3][4]&[5] and hard code the deterioration and print the results and it works, but its pretty crap. How would I improve this method? I'm copy and pasting the 'calculations'. How do I take the first line, then put the following lines in a separate loop?
ideally, the number of days in the text file could vary. ie, there could be 5 races, or there could be 3 and the program will handle both cases.
try something like
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
System.out.println(
"please enter the name of the text file you wish you import. Choose either inputs or lotsainputs. Nothing else");
Scanner keyboard = new Scanner(System.in);
String filename = keyboard.nextLine();
File file = new File(filename);
System.out.println("You have loaded file: \t\t" + filename);
BufferedReader in = new BufferedReader(new FileReader(file));
String element1 = null;
try {
element1 = in.readLine();
}catch (Exception e) {
// TODO: handle exception
}
String[] firstLine = element1.split(" ");
Arrays.stream(firstLine).forEach(fl -> {
System.out.println("First line element: " + fl);
});
//Do the staff
String otherElement = null;
try {
while ((otherElement = in.readLine()) != null) {
System.out.println("Line to process:\t\t" + otherElement);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
result for file:
1 2
3
5
7
is
You have loaded file:
First line element: 1
First line element: 2
Line to process: 3
Line to process: 5
Line to process: 7
I am writing a program to change an input file. It should start a new line after a ? . and ! but I can't seem to figure it out. Each new line should also begin with an Uppercase letter which I think I got. It should also eliminate unnecessary spaces which I also believe I got.
For example: hello? bartender. can I have a drink!whiskey please.
Output should be:
Hello?
Bartender.
Can I have a drink!whiskey please.
It should only make a new line after those operators followed by a whitespace. If there is no space it will not make new line.
import java.util.Scanner;
import java.io.*;
public class TextFileProcessorDemo
{
public static void main(String[] args)
{
String fileName, answer;
Scanner keyboard = new Scanner(System.in);
System.out.println("Test Input File:");
fileName = keyboard.nextLine();
File file = new File(fileName);
PrintWriter outputStream = null;
try
{
outputStream = new PrintWriter(file);
}
catch(FileNotFoundException e)
{
System.out.println("Error opening file" + file);
System.exit(0);
}
System.out.println("Enter a line of text:");
String line = keyboard.nextLine();
outputStream.println(line);
outputStream.close();
System.out.println("This line was written to:" + " " + file);
System.out.println(" ");
TextFileProcessor.textFile();
}
}
Second Class
import java.io.*;
import java.util.Scanner;
public class TextFileProcessor
{
public static void textFile()
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Test Input File:");
String inputFile = keyboard.next();
System.out.print("Output File:");
String outputFile = keyboard.next();
try
{
BufferedReader inputStream = new BufferedReader(new FileReader(inputFile));
PrintWriter outputStream = new PrintWriter(new FileOutputStream(outputFile));
String line = inputStream.readLine();
line = line.replaceAll("\\s+", " ").trim();
line = line.substring(0,1).toUpperCase() + line.substring(1);
//This is where I would like to add code
while(line != null)
{
outputStream.println(line);
System.out.println(line);
line = inputStream.readLine();
}
inputStream.close();
outputStream.close();
}
catch(FileNotFoundException e)
{
System.out.println("File" + inputFile + " not found");
}
catch(IOException e)
{
System.out.println("Error reading from file" + inputFile);
}
}
}
A simple regex would suffice:
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
for(String s:"hello? bartender. can I have a drink!whiskey please.".replaceAll("(\\W)(\\s+)", "$1\n").split("\n"))
System.out.println(s.substring(0, 1).toUpperCase()+s.substring(1));
}
}
Output :
Hello?
Bartender.
Can I have a drink!whiskey please.
https://ideone.com/Zo2N7Q
Would this solve your problem?
if(line.endsWith("! ") || line.endsWith("? ") || line.endsWith(". ")) {
line = line + '\n';
}
You can use a "capture group" in a regex to achieve what you want.
line.replaceAll("(\\? )|(\\! )|(\\. )", "$0\n");
Update:
With regards to your comment on how to capitalize the first character of each line, you can use the toUpperCase method in the Character class.
line = Character.toUpperCase(line.charAt(0)) + line.substring(1);
Note:
If you are using Java 1.7 or above you should consider using a try-with-resources block for the Scanner
try (Scanner keyboard = new Scanner(System.in)) {
...
}
Then when you read input from the user you can manipulate it to the correct format before writing to your file. For example you could do something like...
System.out.println("Enter a line of text:");
String[] lines = keyboard.nextLine().replaceAll("(\\? )|(\\! )|(\\. )", "$0\n").split("\n");
// Replace the first character of each line with an uppercase character
for (int i = 0; i < lines.length; i++) {
lines[i] = Character.toUpperCase(lines[i].charAt(0)) + lines[i].substring(1);
}
Path path = Paths.get(fileName);
Files.write(path, Arrays.asList(lines), Charset.defaultCharset());
System.out.println("This line was written to:" + " " + path.toString());
System.out.println(" ");
As for reading and writing from files you are better off using the non-blocking Files class in the java.nio package. It's as simple as the following;
Path path = Paths.get(fileName);
Files.write(path, Arrays.asList(lines), Charset.defaultCharset());
Then for reading your file you can just use the readAllLines method.
List<String> lines = Files.readAllLines(path);
for (String line : lines ) {
System.out.println(line);
}
I'm trying to create a program that reads in a list of integers from a file, and adds them all together and displays to the user. I can get this program to work properly but what I want to do is have it so if there is an invalid entry in the file (say, a word or anything that isn't a number) it will alert the user and ignore the invalid data and skip to the next available number. Here is my code so far:
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
public class IntegerReadIn {
public static void main(String[] args) {
int sum = 0;
try {
File myFile = new File("IntegerReadIn.txt");
Scanner scan = new Scanner(myFile);
while (scan.hasNextInt()) {
sum = sum + scan.nextInt();
}
System.out.println("Total = " + sum);
scan.close();
} catch (FileNotFoundException e) {
System.err.println("No such file name");
} catch (InputMismatchException e) {
System.err.println("Invalid entry found - integers only.");
}
}
}
First use nextLine() to read the entire line. after that Use Integer.parseInt() method to validate the integer input.
Scanner scan = new Scanner(myFile);
String s = scan.nextLine();
try{
Integer.parseInt(s);
}
catch(NumberFormatException ex){
System.out.println("Error....");
}
Perhaps instead of using your while for only hasNextInt() you should loop for haxNext()
That way you can explicitly check if you get an integer or not (and thus you can provide feedback to the user)
while (scan.hasNext()) {
if (scan.hasNextInt()) {
sum = sum + scan.nextInt();
} else {
System.out.println("Invalid Entry: " + scan.next());
}
}
Having this in consideration you will not be needing the InputMismatchException
I would like to write a paragraph using file.
This is my code(my effort).
import java.io.*;
import java.util.Scanner;
public class Test {
public static void main (String [] args)
{
Scanner input = new Scanner(System.in);
try {
BufferedWriter out = new BufferedWriter(new FileWriter("C:/Users/Akram/Documents/akram.txt")) ;
System.out.println("Write the Text in the File ");
String str = input.nextLine();
out.write(str);
out.close();
System.out.println("File created successfuly");
} catch (IOException e) {
e.printStackTrace();
}
}
}
With this code I can add just one word but I want to add a lot of word (paragraph).
I would use a while loop around Scanner#hasNextLine(). I would also recommend a PrintWriter. So, all together, that would look something like,
Scanner input = new Scanner(System.in);
PrintWriter out = null;
try {
out = new PrintWriter(new FileWriter(
"C:/Users/Akram/Documents/akram.txt"));
System.out.println("Write the Text in the File ");
while (input.hasNextLine()) {
String str = input.nextLine();
out.println(str);
}
System.out.println("File created successfuly");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
In order to write a paragraph, Decide a terminating character or string,Write your code so that it takes the input till that character or string is given in the input, Do some operation to remove the character in the file,
The code which I used is given below,Terminating Character is +
I haven't kept try and catch statements to reduce complexity in understanding
pw = new PrintWriter(new FileWriter("E://files//myfile.txt"));
System.out.println("Write the Text in the File,End the text with + ");
do
{
Scanner sc =new Scanner(System.in);
String S=sc.nextLine();
if(S.endsWith("+"))
{
S= S.replace("+"," ");
flag=1;
pw.println(S);
}
else
pw.println(S);
}while(flag!=1);
Cheers
I'm having issues with a program I'm trying to write. I'm using an arraylist for storing strings and having issues accessing it and writing it to an output file with other data sets so they form uniform columns. The issue I'm having is when I try to access the data in the arraylist and increment it all I get are numbers 1-10 and not the actual data sets. here's my code and the output file.
import java.util.ArrayList;
import java.text.DecimalFormat;
import java.util.Scanner;
import java.io.*;
public class RobertGardner_6_12
{
public static void main(String[] args) throws IOException
{
// Declare variables
// File names
final String INPUT_FILE_NAME = "RobertGardner_6_12_Input.txt";
final String OUTPUT_FILE_NAME = "RobertGardner_6_12 _Output.txt";
// Append current file boolean variable
final boolean APPEND_INDICATOR = false; // Create a new file
double savings = 0; // The sum of the numbers
double debt = 0; // 20% towards debt
double moneyForYou = 0; // 70% for spending
double oneNumber = 0; // A single number read from the file
String processPhrase; // Indicates appending or creating a file
// Access the input and output files
try
{
File inputDataFile = new File(INPUT_FILE_NAME);
Scanner inputScanner = new Scanner(inputDataFile);
}
catch( FileNotFoundException e)
{
System.err.println( "Error opening file.");
}
File inputDataFile = new File(INPUT_FILE_NAME); //Access input
Scanner inputScanner = new Scanner(inputDataFile);
FileWriter outputDataFile = new FileWriter(OUTPUT_FILE_NAME,
APPEND_INDICATOR);
PrintWriter outputFile = new PrintWriter(outputDataFile);
// Access the Toolkit using the variable 'tools'
Toolkit_General tools = new Toolkit_General();
// Format numeric output
DecimalFormat formatter = new DecimalFormat("#,##0.00");
if(APPEND_INDICATOR)
processPhrase = "Appending";
else
processPhrase = "Creating";
// Display file information on console
System.out.println("Reading file " + INPUT_FILE_NAME + "\n"
+ processPhrase + " file " + OUTPUT_FILE_NAME + "\n");
// Display heading in output file
if (inputScanner.hasNext())
{
outputFile.println("Yearly Income Report");
outputFile.println("-----------------------");
}
outputFile.println("Name Income 10% saved " +
"20% to debt Yours to spend");
outputFile.println("------------------------------------------" +
"----------------------------------");
ArrayList<String> list = new ArrayList<String>();
list.add("Donald");
list.add("Jean");
list.add("Christopher");
list.add("Martin");
list.add("Thomas");
list.add("Samuel");
list.add("George");
list.add("Quentin");
list.add("Magaret");
list.add("Toby");
int nameCounter = 0; //
// Read the input file and sum the numbers
while (inputScanner.hasNext())
{
oneNumber = inputScanner.nextDouble();
savings = oneNumber * .1;
debt = oneNumber * .2;
moneyForYou = oneNumber *.7;
list.get(nameCounter);
nameCounter++;
outputFile.println(nameCounter + tools.leftPad(oneNumber, 18, "#0", " ") +
tools.leftPad(savings, 18, "#0", " ")
+ tools.leftPad(debt, 18, "#0", " ") + tools.leftPad(moneyForYou, 18, "#0", " "));
}
// Close files
outputFile.close();
inputScanner.close();
} // End main
} // End class
when I output the data it looks something like this:
1 100000 10000 20000 70000
when I want the output to say:
Donald 100000 10000 20000 70000
and so forth using all the strings within the arraylist.
when you retrieve the value from the list you do not save it to a variable
try
String name = list.get (nameCounter);
outputFile.println (name + ....
Also change this code
// Access the input and output files
try {
File inputDataFile = new File(INPUT_FILE_NAME);
Scanner inputScanner = new Scanner(inputDataFile);
} catch (FileNotFoundException e) {
System.err.println("Error opening file.");
}
File inputDataFile = new File(INPUT_FILE_NAME); //Access input
Scanner inputScanner = new Scanner(inputDataFile);
to
// Access the input and output files
Scanner inputScanner = null;
try {
File inputDataFile = new File(INPUT_FILE_NAME);
inputScanner = new Scanner(inputDataFile);
} catch (FileNotFoundException e) {
System.err.println("Error opening file.");
e.printStackTrace();
return; // no point in continuing
}
int nameCounter = 0;
while (inputScanner.hasNext()) {
//...
list.get(nameCounter); //<-- This line returns something.
// But you never keep a reference to it!
// So how do you expect to do anything with it?
nameCounter++;
//...
}
when I try to access the data in the arraylist and increment it"
You can't increment Strings.
all I get are numbers 1-10
That's because here:
outputFile.println(nameCounter + tools.leftPad(...)...);
^^^^^^^^^^^
You're printing nameCounter, and not the name you want
What you probably want to do is save the value of list.get(nameCounter) into a String, then use that variable instead of nameCounter in your print statement.