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
Related
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);
}
}
}
I am trying to figure out how to make a grep method that can read wrapped phrases from up-to infinity lines(That is a sentence or string spanning multiple lines of a given text file) in java. Here is my current code for the grep function:
public static void grep() throws IOException{
BufferedReader f = new BufferedReader(new FileReader("Cabbages.txt"));
Scanner in = new Scanner(System.in);
String line = "", input = "", wrappedPhrase = "", modified = "";
int c = 0, foundCount = 0;
boolean found = false;
System.out.print("Please enter something you want to grep: ");
input = in.nextLine();
while((line = f.readLine()) != null) {
c++;
found = false;
int index = line.indexOf(input);
while(index >= 0) {
modified = "<" + line.substring(line.indexOf(input), (line.indexOf(input)+input.length())) + ">";
found = true;
index = line.indexOf(input, index + 1);
foundCount++;
}
if(found) {
System.out.println("Found on line: " + c + ", which is: " + line.replace(input, modified));
}
}
if(foundCount <= 0) {
System.out.println("Sorry, the input string of: \"" + input + "\" was not found within the given file.");
}else {
System.out.println("In total, the input string of: \"" + input + "\"" + " was found " + foundCount + " time(s).");
}
}
I need to access 'sets' outside the first for loop. How can i do that?
I want to sort on the result but i am not bale to access the result 'sets' outside the for loop. if I sort it inside, I am not getting the sort result as expected.
static Set < String > generateReports() {
try {
String[] parts2;
String part2 = null;
String[] parts3;
String part3 = null;
// String sets = null;
for (i = 1; i < 3; i++) {
String line = null;
FileReader fileReader1 = new FileReader("C:/Projects/Wells Fargo IVR/TestFolder/" + (i) + ".log");
BufferedReader bufferedReader1 = new BufferedReader(fileReader1);
while ((line = bufferedReader1.readLine()) != null) {
String string = line;
parts2 = string.split("-");
if (parts2.length > 4) {
part2 = parts2[4];
sids.put(part2, line);
// System.out.println(sids.get(part2));
}
// if(IVRLogFileMerge.getSid().contains(part2)){
if (testSet.contains(part2)) {
// System.out.println("This is file number" + (i)+ " " + line);
for (String current: testSet1) {
if (line.contains(current)) {
//System.out.println(line);
testSetFinal.add(line);
String string1 = line.replace(" ", " ");
String string2 = string1.replace("default task", "Thread");
parts3 = string2.split(" ");
sets = (parts3[1] + " " + parts3[6] + " " + parts3[8] + " ");
//System.out.print(parts3[1] + " " + parts3[6] + " " + parts3[8] + " ");
for (int j = 10; j < parts3.length; j++) {
//System.out.print(parts3[j] + " ");
// bufferWritter.write(parts3[j] + " ");
sets = sets.concat(parts3[j] + " ");
}
FileWriter fileWritter = new FileWriter("C:/Projects/Wells Fargo IVR/TestFolder/file.txt", true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(sets);
bufferWritter.newLine();
bufferWritter.close();
// System.out.println();
String[] str = new String[] {
sets
};
Arrays.sort(str);
for (String s: str) {
//System.out.println(i + " " + s);
}
}
}
}
//bufferedWriter.write("This is file number" + (i)+ " " + line);
//bufferedWriter.newLine();
}
bufferedReader1.close();
}
//System.out.println(testSetFinal);
You have String sets = null; commented out currently. Uncomment that, and switch it to
String sets = "";
I need to write 100 integers created randomly into a file using Java I/O
this is my code so far:
package lab;
import java.util.*;
import java.io.*;
public class test {
public static void main(String[] args) {
Random num = new Random();
try {
File file = new File("E:\\Test.txt");
if(file.exists()) {
file.createNewFile();
}
PrintWriter out = new PrintWriter(new File("E:\\Test.txt"));
for (int i = 0; i <= 9; i++){
output.print(num.nextInt(100)+" "+num.nextInt(100) + " " +
num.nextInt(100) + " " + num.nextInt(100) + " " + num.nextInt(100) + " "
+ num.nextInt(100) + " " + num.nextInt(100) + " " + num.nextInt(100) + " "
+ num.nextInt(100) + " " + num.nextInt(100));
output.println();
}
out.close();
Scanner input = new Scanner(file);
while(input.hasNext()) {
System.out.println(input.nextLine());
}
input.close();
}
catch (IOException ex) {
System.out.println("File Already Exists!");
}
}
}
I need to simplify the "for-loop", and be able to read back the file to display it.
Can anyone help?
First of all do not concatenate Strings in for loops (new objects are created), use StringBuilder.
Once you build your string with random numbers save it like this:
http://www.mkyong.com/java/how-to-write-to-file-in-java-bufferedwriter-example/
StringBuilder str = new StringBuilder();
Random rng = new Random();
for (int i = 0; i < 100; ++i)
str.append(rng.nextInt(100) + " ");
System.out.println(str.toString());
Replace System.out.println(str.toString()); with your filestream writing.
File file = new File("File_name.txt");
StringBuilder str = new StringBuilder();
try (PrintWriter output = new PrintWriter(file);) {
for (int i = 0; i < 100; i++) {
int num = ((int)(Math.random() * 500) + 1);
output.print(num);
output.print(" ");
str.append(num + " ");
}
}
System.out.println(str.toString());
Like the title says, I can get it to write the first thing to the file I want it to, but after that it doesn't write any more. I run it through the debugger, and see that it's not even reading the next line (I know this because it's not filling the array.) I tried manually advancing the pointer (I don't know if that's actually a thing you can do) at the end of the loop with "line = in.readline;", but It just throws a "nosuchelement" exception. Here's my try block"
try
{
in = new BufferedReader(new FileReader("lab7input.txt"));
outNormal = new PrintWriter(new File("normal.txt"));
outVegetarian = new PrintWriter(new File("vegetarian.txt"));
outPescetarian = new PrintWriter(new File("pescetarian.txt"));
outInvalid = new PrintWriter(new File("invalid.txt"));
String line = in.readLine();
StringTokenizer st = new StringTokenizer(line);
while (line != null)
{
Scanner sc = new Scanner(line);
while(sc.hasNext())
{
if(st.countTokens() == 3)
{
attendee3[0] = sc.next();
attendee3[1] = sc.next();
attendee3[2] = sc.next();
if(Integer.parseInt(attendee3[2]) == 0)
{
outNormal.println(attendee3[0] + " " + attendee3[1]);
outNormal.close();
}
else if(Integer.parseInt(attendee3[2]) == 1)
{
outVegetarian.println(attendee3[0] + " " + attendee3[1]);
outVegetarian.close();
}
else if(Integer.parseInt(attendee3[2]) == 2)
{
outPescetarian.println(attendee3[0] + " " + attendee3[1]);
outPescetarian.close();
}
else
{
outInvalid.println(attendee3[0] + " " + attendee3[1]);
outInvalid.close();
}
}
if(st.countTokens() == 4)
{
attendee4[0] = sc.next();
attendee4[1] = sc.next();
attendee4[2] = sc.next();
if(Integer.parseInt(attendee4[3]) == 0)
{
outNormal.println(attendee4[0] + " " + attendee4[1] + " " + attendee4[2]);
outNormal.close();
}
else if(Integer.parseInt(attendee4[3]) == 1)
{
outVegetarian.println(attendee4[0] + " " + attendee4[1] + " " + attendee4[2]);
outVegetarian.close();
}
else if(Integer.parseInt(attendee4[3]) == 2)
{
outPescetarian.println(attendee4[0] + " " + attendee4[1] + " " + attendee4[2]);
outPescetarian.close();
}
else
{
outInvalid.println(attendee4[0] + " " + attendee4[1] + " " + attendee4[2]);
outInvalid.close();
}
}
//line = in.readLine();
}
}
}
a simpler and cleaner way would be
String line = in.readLine();
while (line != null)
{
String arr [] = line.split ();
if(arr.length == 3)
{
attendee3[0] = arr[0];
attendee3[1] = arr[1];
attendee3[2] = arr[2];
}
// other count code
line = in.readLine();
}
You have to put line = in.readLine() one block below and not in a while block of a scanner.
Not only that, i've had the experience that Scanner can only read in UTF-8 codeded .txt files. so always make sure that they are UTF-8 coded.
If they are not just simply open the file and save it with that coding.