Reading And Writing to text file - java

I've written this code to read in a file and then ask for a mark, for each name in the file. And if the mark is over 40 its a pass and below is a fail and writes each name to the corresponding file. But I get an error at line 27 which: while(namesFile.hasNext() here's my code:
import java.io.*;
import java.util.*;
public class TestResults {
public static void main(String[] args) {
String errs = "";
Scanner k = new Scanner(System.in);
try {
try (
Scanner namesFile = new Scanner(new File("Names.txt"));
PrintWriter passFile = new PrintWriter("Pass.txt");
PrintWriter failFile = new PrintWriter("Fail.txt");) {
while (namesFile.hasNext()) {
try {
String tempLine = namesFile.nextLine();
System.out.println("Please Enter Mark For " + tempLine + " : ");
int mark = k.nextInt();
if (mark >= 40) {
passFile.println(tempLine + " " + mark + "%");
} else {
failFile.println(tempLine + " " + mark);
}
} catch (InputMismatchException ime) {
String valueStr = namesFile.next();
errs += "\n\t" + valueStr;
} finally {
namesFile.close();
passFile.close();
failFile.close();
}
}
}
} // Checks to see if file is there.
catch (IOException ioe) {
System.out.println("ERROR: " + ioe.getMessage());
}
}
}

public class TestResults {
public static void main(String[] args) {
Scanner namesFile;
PrintWriter passFile;
PrintWriter failFile;
String errs = "";
Scanner k = new Scanner(System.in);
try {
try {
namesFile = new Scanner(new File("D:/Names.txt"));
passFile = new PrintWriter("D:/Pass.txt");
failFile = new PrintWriter("D:/Fail.txt");
try {
while (namesFile.hasNext()) {
String tempLine = namesFile.nextLine();
System.out.println("Please Enter Mark For " + tempLine + " : ");
int mark = k.nextInt();
if (mark >= 40) {
passFile.println(tempLine + " " + mark + "%");
} else {
failFile.println(tempLine + " " + mark);
}
}
} catch (InputMismatchException ime) {
String valueStr = namesFile.next();
errs += "\n\t" + valueStr;
} finally {
namesFile.close();
passFile.close();
failFile.close();
}
}
catch(IOException ioe){
System.out.println("ERROR: " + ioe.getMessage());
}
} // Checks to see if file is there.
catch (Exception e) {
}
}
}

Related

how to stop a process when "ctrl+c" is pressed in java?

i am using the following in one of my application.
public static void concatenation(List<String> commands) throws IOException {
if (commands.get(1).equals(">")) {
String path = history.getFilePath();
File file = new File(path + "\\" + commands.get(2));
if (file.exists() && file.isFile()) {
try (FileWriter writer = new FileWriter(file)) {
Scanner scanner = new Scanner(System.in);
String line;
System.out.println("Write to file. Press Ctrl+C to stop.");
while (true) {
try {
line = scanner.nextLine();
writer.write(line + System.lineSeparator());
writer.flush();
} catch (Exception e) {
System.out.println("Interrupted. Stopping...");
break;
}
}
scanner.close();
} catch (IOException e) {
System.out.println("Error writing to file: " + e.getMessage());
}
}
} else {
System.out.println("bash : " + commands.get(1) + " : unrecognized operator");
}
}
i want to exit out of the while loop when ctrl + c is pressed. And it is a console application. How to achieve this?

Read File and extract to different output

I have the following data. What I'm trying to do is to separate every reading into different outputs, but it does not work. It only show 'null'. What i expected to work are:
Output:
C.txt
1 1000 1000
2 2000 2000
Output: B.txt
1 2 90.000 2
2 3 180.000 2
Output: D.txt
1 2 100.1 0.038
2 3 200.1 0.038
Data in Input.txt:
C;1;1000;1000
C;2;2000;2000
B;1;2;90.00;2
B;2;3;180.00;2
D;1;2;100.1;0.038
D;2;3;200.1;0.038
import java.io.*;
import java.util.StringTokenizer;
public class ReadFile {
public static void main(String[] args) {
BufferedReader input = null; //read
PrintWriter outC = null; //write output
PrintWriter outB = null;
PrintWriter outD = null;
try {
input = new BufferedReader(new FileReader("C:\\Users\\PC\\Desktop\\FYP\\Input.txt"));
outC = new PrintWriter(new BufferedWriter(new FileWriter("C:\\Users\\PC\\Desktop\\FYP_Test\\C.txt")));
outB = new PrintWriter(new BufferedWriter(new FileWriter("C:\\Users\\PC\\Desktop\\FYP_Test\\B.txt")));
outD = new PrintWriter(new BufferedWriter(new FileWriter("C:\\Users\\PC\\Desktop\\FYP_Test\\D.txt")));
String inputData = null;
int C = 0;
int B = 0;
int D = 0;
while ((inputData = input.readLine()) != null) {
StringTokenizer tokenizer = new StringTokenizer(inputData, ";");
String id = tokenizer.nextToken();
String StnFrom = tokenizer.nextToken();
String NorthingTo = tokenizer.nextToken();
String EastingDistBrg = tokenizer.nextToken();
String StdError = tokenizer.nextToken();
if (id.equalsIgnoreCase("C")) {
C++;
outC.println(StnFrom + " " + NorthingTo + " " + EastingDistBrg);
} else if (id.equalsIgnoreCase("B")) {
B++;
outB.println(StnFrom + " " + NorthingTo + " " + EastingDistBrg + " " + StdError);
} else if (id.equalsIgnoreCase("D")) {
D++;
outB.println(StnFrom + " " + NorthingTo + " " + EastingDistBrg + " " + StdError);
}
}
input.close();
outC.close();
outB.close();
outD.close();
} catch (FileNotFoundException fe) {
System.out.println(fe.getMessage());
} catch (IOException iox) {
System.out.println(iox.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
tokenizer.nextToken() will throw NoSuchElementException when there are no more tokens in the tokenizer's string.
Your sample input, if provided, will throw "NoSuchElementException" because Data in "Input.txt" for "C" is wrong. In your program, you are calling "nextToken" five times, whereas data for "C" contains only 4 values(C;1;1000;1000).
Below, is improved "Input" data.
C;1;1000;1000;1
C;2;2000;2000;1
B;1;2;90.00;2
B;2;3;180.00;2
D;1;2;100.1;0.038
D;2;3;200.1;0.038
Also, you need to improve your while loop to read empty line. Currently, it will throw Error.
Consider below while loop:
while ((inputData = input.readLine()) != null) {
if(inputData.length() != 0) {
StringTokenizer tokenizer = new StringTokenizer(inputData, ";");
String id = tokenizer.nextToken();
String StnFrom = tokenizer.nextToken();
String NorthingTo = tokenizer.nextToken();
String EastingDistBrg = tokenizer.nextToken();
String StdError = tokenizer.nextToken();
if (id.equalsIgnoreCase("C")) {
C++;
outC.println(StnFrom + " " + NorthingTo + " " + EastingDistBrg);
} else if (id.equalsIgnoreCase("B")) {
B++;
outB.println(StnFrom + " " + NorthingTo + " " + EastingDistBrg + " " + StdError);
} else if (id.equalsIgnoreCase("D")) {
D++;
outD.println(StnFrom + " " + NorthingTo + " " + EastingDistBrg + " " + StdError);
}
}
}

Exception Handling optimization in java

I want to create a program that handles the 3 possible exceptions that occur when dividing two ints, asking the user to correct the input if it triggers an exception. The code only executes if no exceptions are triggered. The following code works, but I feel it is too unoptimized. Is there no other way, other than while loops, to continuously check for exceptions?
import javax.swing.JOptionPane;
public class DivisionExceptions {
public int divide(int num, int den) {
return num/den;
}
public static void main(String[] args) {
int num = 0,
den = 0,
a = 0,
b = 0,
c = 0;
DivisionExceptions div = new DivisionExceptions();
while(a == 0) {
try {
num = Integer.parseInt(JOptionPane.showInputDialog("Introduce the first int"));
a++;
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Error of type: " + e.getMessage() + ". Verify the information and try again.");
}
}
while (c == 0) {
b = 0;
while(b == 0) {
try {
den = Integer.parseInt(JOptionPane.showInputDialog("Introduce the second int"));
b++;
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Error of type: " + e.getMessage() + ". Verify the information and try again.");
}
}
try {
JOptionPane.showMessageDialog(null, "Result of dividing: " + num + "/" + den + " is " + div.divide(num, den));
c++;
}
catch (ArithmeticException e) {
JOptionPane.showMessageDialog(null, "Error of type: " + e.getMessage() + ". Verify the information and try again.");
}
}
}
}
Could be simplified to:
public static void main(String[] args) {
int num = 0, den = 0;
DivisionExceptions div = new DivisionExceptions();
while(true) {
try {
num = Integer.parseInt(JOptionPane.showInputDialog("Introduce the first int"));
break;
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Error of type: " + e.getMessage() + ". Verify the information and try again.");
}
}
while (true) {
try {
den = Integer.parseInt(JOptionPane.showInputDialog("Introduce the second int"));
JOptionPane.showMessageDialog(null, "Result of dividing: " + num + "/" + den + " is " + div.divide(num, den));
break;
} catch (NumberFormatException | ArithmeticException e) {
JOptionPane.showMessageDialog(null, "Error of type: " + e.getMessage() + ". Verify the information and try again.");
}
}
}
~
Well your code could use some refactor.
public class DivisionExceptions {
public int divide(int num, int den) {
return num / den;
}
public static void main(String[] args) {
int num = 0,
den = 0,
a = 0,
b = 0,
c = 0;
DivisionExceptions div = new DivisionExceptions();
num = getNum(a, "Introduce the first int");
den = getNum(b, "Introduce the second int");
while (c == 0) {
try {
JOptionPane.showMessageDialog(null, "Result of dividing: " + num + "/" + den + " is " + div.divide(num, den));
c++;
} catch (ArithmeticException e) {
JOptionPane.showMessageDialog(null, "Error of type: " + e.getMessage() + ". Verify the information and try again.");
}
}
}
private static int getNum( int loopParam, String message) {
int num = 0;
while (loopParam == 0) {
try {
num = Integer.parseInt(JOptionPane.showInputDialog(message));
loopParam++;
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Error of type: " + e.getMessage() + ". Verify the information and try again.");
}
}
return num;
}
}
I also allow myself to extract den calculation from while(c==0) loop, because it always calculates same value but for n times, so you gain some optimilization here. If you can provide more information about why do you predefine all of your params as 0, than perhaps I could find some solution for that while(c==0) loop. If you use java 8 you could also extract your while loop to another method and give some Function as a param.

Java File Handling Editing records

I made a code for my system which would update a record in my text file database but I cant seem to make it work. The code doesnt have any error. its just not doing what I intend it to do
public static void Update() throws Exception {
File tempfile2 = new File("temp.txt");
tempfile2.createNewFile();
FileInputStream tempFStream = new FileInputStream(tempfile2);
BufferedReader read = new BufferedReader(new InputStreamReader(tempFStream));
System.out.print("Product Number: ");
String searchnum = br.readLine();
try {
LoadFile();
boolean found = false;
for (int i = 0; i < row; i++) {
String record[] = list.get(i).split(",");
if (!searchnum.equals(record[0])) {
found = true;
FileWriter fw = new FileWriter(tempfile2, true);
fw.write(record[0] + "," + record[1] + "," + record[2] + "," + record[3] + "," + record[4] + "," + record[5] + "\r\n");
fw.close();
}
}
for (int i = 0; i < row; i++) {
String record[] = list.get(i).split(",");
if (searchnum.equals(record[0])) {
found = true;
System.out.println("\t\t\t*******************************");
System.out.println("\t\t\t PIXBOX PHOTOBOOTH");
System.out.println("\t\t\t*******************************");
System.out.println("\n\t\t\tRecord Found:");
System.out.println("\n\t\t\tProduct Number : " + record[0]);
System.out.println("\t\t\tCategory : " + record[1]);
System.out.println("\t\t\tProduct Name : " + record[2]);
System.out.println("\t\t\tPrice [m/d/y] : " + record[3]);
System.out.println("\t\t\tQuantity : " + record[4]);
System.out.println("\n\n\t\t\t--------------------------------");
System.out.print("\t\t\tAre you sure you want to replace the records?<Y/N>: ");
String del = br.readLine();
if (del.equals("Y") || del.equals("y")) {
LoadFile();
System.out.println("\t\t\t*******************************");
System.out.println("\t\t\t PIXBOX PHOTOBOOTH");
System.out.println("\t\t\t*******************************");
System.out.println("\n\n\t\t\t------Update Record Form------");
System.out.print("\n\n\t\t\tProduct Number : ");
int prodnum = Integer.parseInt(br.readLine());
System.out.print("\t\t\tCategory : ");
String cat = br.readLine();
System.out.print("\t\t\tProduct Name :");
String prodname = br.readLine();
System.out.print("\t\t\tPrice: ");
String price = br.readLine();
System.out.print("\t\t\tQuantity : ");
String quan = br.readLine();
read.close();
database.delete();
boolean rename = false;
if (rename = tempfile2.renameTo(database)) {
InsertRecords(prodnum, cat, prodname, price, quan);
System.out.println("\t\t\tSuccessfully Edited!");
exiting();
} else {
System.out.print("Edit Failed!");
}
} else if (del.equals("N") || del.equals("n")) {
MainMenu();
}
}
if (!searchnum.equals(record[1])) {
System.out.println("\n\t\t\tNo Record Found.");
Thread.sleep(2000);
exiting();
}
}
} catch (Exception e) {
System.out.print("File Empty!");
}
}
public static void LoadFile()throws Exception
{
list.clear();
FileInputStream fis = new FileInputStream(database);
BufferedReader read = new BufferedReader(new InputStreamReader(fis));
row = 0;
while(read.ready())
{
list.add(read.readLine());
row++;
}
read.close();
}
Everytime I run this... it would work until Product Number: User input and after entering a number it would directly display File is empty which is at the end of the program. its as if the try/catch is ignored. I definitely did something wrong but I dont know what I did wrong. Anyone shed me some light? Thanks
and with the e.printStackTrace(); here's what displayed after entering a product number...
java.lang.ArrayIndexOutofBoundException:5
at SnackTimeInventorySystem.Update<SnackTimeInventorySystem.java:525>
at SnackTimeInventorySystem.MainMenu<SnackTimeInventorySystem.java:66>
at SnackTimeInventorySystem.Login<SnackTimeInventorySystem.java:369>
at SnackTimeInventorySystem.main<SnackTimeInventorySystem.java:14>
Turns out I only had 5 entries on my array but declared 6 entries to be written
System.out.println("\t\t\t*******************************");
System.out.println("\t\t\t PIXBOX PHOTOBOOTH");
System.out.println("\t\t\t*******************************");
System.out.println("\n\t\t\tRecord Found:");
System.out.println("\n\t\t\tProduct Number : " + record[0]);
System.out.println("\t\t\tCategory : " + record[1]);
System.out.println("\t\t\tProduct Name : " + record[2]);
System.out.println("\t\t\tPrice [m/d/y] : " + record[3]);
System.out.println("\t\t\tQuantity : " + record[4]);
System.out.println("\n\n\t\t\t--------------------------------");
fw.write(record[0] + "," + record[1] + "," + record[2] + "," + record[3] + "," + record[4] + "," + record[5] + "\r\n");
So I just had to delete record[5] and fixed the problem thanks to Tom

Iterating though a text file in Java so that each line has information about that line

Ok, so I really didn't know how to say it right for the title so this should shed some light on the situation.
I'm making a palindrome program in Java. In every which way you look at it, it works just fine. It reads in a file using Scanner, searches through the entire file and outputs if that line in the text file is a palindrome. If you have any special characters or caps it deletes them and turns everything to lowercase.
My issue is that after the check is done on each line, I want to show some extra information next to the result.
Each line should show how many words are in the line, how many characters and if its a palindrome or not.
Anyway here is the code, hopefully someone can help me figure this out. Thanks.
import java.io.File;
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
//Global Variables
Scanner cScan = null;
Scanner wScan = null;
Scanner pScan = null;
int charCount = 0, numLines = 0, numChars = 0, wordCount = 0;
//Take in User Input
Scanner iScan = new Scanner(System.in); //Start input Scanner
String fileName = null;
System.out.print("Please Enter a File Name: ");
fileName = iScan.nextLine();
iScan.close(); //Close input Scanner
//Read File Specified by User
File palin = new File(fileName);
try {
//Checks for Number of Characters
cScan = new Scanner(palin);
while(cScan.hasNextLine()) {
String line = cScan.nextLine();
numChars += line.length();
numLines++;
}
//Checks for Number of Words
wScan = new Scanner(palin);
while (wScan.hasNext()) {
wScan.next();
wordCount++;
}
//Format Lines
pScan = new Scanner(palin);
while (pScan.hasNext()) {
String line = pScan.nextLine();
String reString = line.replaceAll("[^\\p{L}\\p{Nd}]", "");
String lString = reString.toLowerCase();
boolean pali = false;
String tP = "Yes", fP = "No";
int n = lString.length();
for (int i = 0; i < (n / 2) + 1; ++i) {
if (lString.charAt(i) != lString.charAt(n - i - 1)) {
pali = false;
break;
}
else if (lString.charAt(i) == lString.charAt(n - i - 1)) {
pali = true;
break;
}
}
if (pali == true)
System.out.println(line + " w: " + wordCount + ", " + " c: " + charCount + ", " + tP);
else
System.out.println(line + " w: " + wordCount + ", " + " c: " + charCount + ", " + fP);
}
}
catch(Exception e) {
System.out.println("File Could Not be Found");
}
//charCount = (numLines + numChars) - 1; //Minus 1 to Compensate for EOL at EOF
//System.out.println(charCount);
//System.out.println(wordCount);
//System.out.println(spRemover);
}
}
I cleaned up your code a little bit.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Palindrome {
int charCount = 0;
int totalWordCount = 0;
public static String isPalindrome(String str) {
if(str.equals(new StringBuffer().append(str).reverse().toString())) {
return "a";
}
else {
return "not a";
}
}
public static int getNumberOfWords(String str) {
return str.isEmpty() ? 0 : str.split("\\s+").length;
}
public void process(File file) {
try {
Scanner sc = new Scanner(file);
int i = 0;
while(sc.hasNextLine()) {
i++;
String line = sc.nextLine();
int wordCount = getNumberOfWords(line);
System.out.println("Line " + i + "is " + isPalindrome(line) + " palindrome. It has " + wordCount + " words and " + line.length() + " characters.");
charCount = charCount + line.length();
totalWordCount = totalWordCount + wordCount;
}
sc.close();
System.out.println("There are " + i + " lines in the file with a total of " + totalWordCount + " words and " + charCount + " characters.");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Scanner iScan = new Scanner(System.in);
String fileName = null;
System.out.print("Please Enter a File Name: ");
fileName = iScan.nextLine();
iScan.close();
File file = new File(fileName);
Palindrome pal = new Palindrome();
pal.process(file);
}
}
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class IteratingFileWithInformation {
int charCount = 0 ;
int totalWordCount = 0;
private static String checkPalindrome(String line) {
return line.equals(new StringBuffer().append(line).reverse().toString()) ? "a" : "not a" ;
}
private static int getNumberOfWords(String words) {
return words.isEmpty() ? 0 : words.split("\\s+").length;
}
private void checkFileAndProcess(BufferedReader file) {
Scanner input = new Scanner(file);
int i = 0;
while(input.hasNextLine()) {
i++;
String line = input.nextLine();
int wordCount = getNumberOfWords(line);
System.out.println("Line: " + i + " is " + checkPalindrome(line) + " Palindrome. It has " + wordCount + " words and " + line.length() +
" characters. ");
charCount += line.length();
totalWordCount += wordCount;
}
input.close();
System.out.println("There are " + i + " lines in the file with a total of " + totalWordCount + " words and " + charCount + " characters.");
}
public static void main(String[] args) throws FileNotFoundException {
Scanner givefileName = new Scanner(System.in);
String fileName = null;
System.out.println("Enter the file name :");
fileName = givefileName.nextLine();
givefileName.close();
FileReader file = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(file);
IteratingFileWithInformation fileWithInformation = new IteratingFileWithInformation();
fileWithInformation.checkFileAndProcess(bufferedReader);
}
}

Categories

Resources