Related
I have to display all of records in my blocks (text files), and do a split to "cover" the Fields Separators, but only the first record of my blocks are diplayed. What am I doing wrong?
enter code here
public static void listAllStudents() throws IOException {
File path = new File(Descriptor.getBlockPath());
for (int i = 0; i < path.listFiles().length; i++) {
try {
FileInputStream file = new FileInputStream(Descriptor.getBlockPath() + "BLK" + i + ".txt");
InputStreamReader entrada = new InputStreamReader(file);
BufferedReader buf= new BufferedReader(entrada);
String piece = " ";
System.out.println("\nBLOCO " + i + " ------------------------------------------------------ +");
do {
if (buf.ready()) {
piece = buf.readLine();
System.out.println("\n¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨");
String string = " ", field[] = piece.split(Descriptor.getFieldSeparator());
string = " ";
System.out.println("CPF: " + field[0]);
System.out.println("Name: " + field[1]);
System.out.println("Course: " + field[2]);
System.out.println("Age: " + field[3]);
System.out.println("Phone: " + field[4]);
System.out.println("Active: " + field[5]);
string = " ";
}
} while (buf.ready());
buf.close();
} catch (IOException e) {
System.out.println();
}
}
}
See the documentation for the BufferedReader.readLine() method:
or null if the end of the stream has been reached
Then change your code to read the file line by line:
while ((piece = buf.readLine()) != null) {
String field[] = piece.split(Descriptor.getFieldSeparator());
if (field.length >= 6) {
System.out.println("CPF: " + field[0]);
System.out.println("Name: " + field[1]);
System.out.println("Course: " + field[2]);
System.out.println("Age: " + field[3]);
System.out.println("Phone: " + field[4]);
System.out.println("Active: " + field[5]);
}
}
I need some assistance with my program. Using an example program that was similar I was able to get the basic layout of everything I needed to do. Right now my main questions is if my code is correct for the first part. I want it to read the data from my data file into a parallel array. I included my entire program for reference of the layout, but for now I'm just trying to read the data file into an array. Any help is greatly appreciated. Let me know if more information is needed or if my formatting is wrong.
Data File (patient.txt):
11111,Smith,Norris,Thyroid,1000.00
11112,Obama,Norris,Lasek,500.00
11113,Hoover,Norris,Dental,100.00
11114,Cena,Norris,Lasek,500.00
11115,Leto,Norris,Thyroid,1000.00
22221,Clark,Bond,Thyroid,1000.00
22222,Chang,Bond,Lasek,500.00
22223,Dent,Bond,Dental,100.00
22224,Nixon,Bond,Lasek,500.00
22225,Washington,Bond,Dental,100.00
33331,Jones,Lee,Dental,100.00
33332,Ross,Lee,Lasek,500.00
33333,Gates,Lee,Thyroid,1000.00
33334,Johnson,Lee,Thyroid,1000.00
33335,Carter,Lee,Dental,100.00
Program (class is Patient_Reports)
`
import javax.swing.JOptionPane;
import java.io.*;
import java.util.*;
public class Patient_Reports {
public static void main(String[] args)
{
int selection;
String pnumber;
Patient_Reports patient = new Patient_Reports();
patient.start_system();
pnumber = patient.menu();
selection = Integer.parseInt(pnumber);
while(selection !=3)
{
if(selection==1)
patient.All_Information_Report();
else
if(selection==2)
patient.Surgeries_Doctor_Report();
else
if(selection==3)
patient.Surgeries_Type_Report();
else
if(selection==4)
patient.Doctor_Fees_Report();
else
if(selection==5)
patient.Average_Fees_Report();
pnumber = patient.menu();
selection = Integer.parseInt(pnumber);
}//while loop
patient.Exit();
System.exit(0);
}//main method
//Read Data File
int count=-1,i;
int [] id = new int [10];
String [] patient = new String [10];
String [] doctor = new String [10];
String [] surgery = new String [10];
double [] cost = new double [10];
void start_system()
{
String newLine;
try
{
//define a file valiable for Buffered read
BufferedReader Patient_Reports = new BufferedReader(new FileReader("patient.txt"));
//read lines in file until there are no more lines in the file to read
while ((newLine = Patient_Reports.readLine()) != null)
{
//there is a "," between each data item in each line
StringTokenizer delimiter = new StringTokenizer(newLine,",");
count=count+1;
id[count] = Integer.parseInt(delimiter.nextToken());
patient[count] =delimiter.nextToken();
doctor[count] =delimiter.nextToken();
surgery[count] =delimiter.nextToken();
cost[count] = Double.parseDouble(delimiter.nextToken());
}//while loop
Patient_Reports.close();
}//end try
catch (IOException error)
{
//there was an error on the file writing
System.out.println("Error on file read " + error);
}//error on read
}//end start_system
//Method for Menu of Reports
String menu()
{
String pnum;
String Output = "Reports" + "\n" +"1. All_Information_Report" + "\n" +
"2. Surgeries_Doctor_Report" + "\n" +
"3. Surgeries_Type_Report" + "\n" +
"4. Doctor_Fees_Report" + "\n" +
"5. Average_Fees_Report" + "\n" +
"6. Exit" + "\n" +
" " + "\n" +
"Select a Report >";
pnum = JOptionPane.showInputDialog(null,
Output, "",JOptionPane.QUESTION_MESSAGE);
return pnum;
}//end menu
/* Placeholder for the Reports
//All_Information_Report Report containing all of the information
void All_Information_Report()
{
System.out.println("All_Information_Report");
for (i=0; i<=count; ++i)
{
System.out.println(id[i] + " " + patient[i] + " " + doctor[i] + " " + surgery[i] + " " + cost[i] + " ");
}//for loop
}//end report
//Surgeries_Doctor_Report Report on all surgeries of a specific doctor (prompt for the doctor)
void Surgeries_Doctor_Report()
{
System.out.println("Surgeries_Doctor_Report");
for (i=0; i<=count; ++i)
{
System.out.println(id[i] + " " + patient[i] + " " + doctor[i] + " " + surgery[i] + " " + cost[i] + " ");
}//for loop
}//end report
//Surgeries_Type_Report Report on all surgeries of a specific type(Prompt for the surgery type)
void Surgeries_Type_Report()
{
System.out.println("Surgeries_Type_Report");
for (i=0; i<=count; ++i)
{
System.out.println(id[i] + " " + patient[i] + " " + doctor[i] + " " + surgery[i] + " " + cost[i] + " ");
}//for loop
}//end report
//Doctor_Fees_Report Report on the total amount of fees paid to each doctor
void Doctor_Fees_Report()
{
System.out.println("Doctor_Fees_Report");
for (i=0; i<=count; ++i)
{
System.out.println(id[i] + " " + patient[i] + " " + doctor[i] + " " + surgery[i] + " " + cost[i] + " ");
}//for loop
}//end report
//Average_Fees_Report Report on the Average Fee
void Average_Fees_Report()
{
System.out.println("Average_Fees_Report");
for (i=0; i<=count; ++i)
{
System.out.println(id[i] + " " + patient[i] + " " + doctor[i] + " " + surgery[i] + " " + cost[i] + " ");
}//for loop
}//end report
*/
//Store Data File in Array
void Exit()
{
try
{
BufferedWriter Patient_Reports = new BufferedWriter(new FileWriter("patient.txt"));
for (i=0; i<=count; ++i)
{
//put "," between each data item in the file
Patient_Reports.write(id[i] + "," + patient[i] + "," + doctor[i]+ "," + surgery[i] + ","+ cost[i]+ ",");
//write a new line in the file
Patient_Reports.newLine();
}//for loop
Patient_Reports.close();
}//end try
catch (IOException error)
{
//there was an error on the write to file
System.out.println("Error on file write " + error);
}//end error
}//end class
}//end exit_system`
To begin, your code is VERY confusing and violates several OOP programming conventions.
The first (and most egregious) problem is that your static class Patient_Reports contains the main method but does not utilize this static entry point to declare an object or advance. So, it would behoove you to reformat your code like this:
public class Patient_Reports {
Patient_Reports fields...
public Patient_Report() {
//start work here in Constructor
}
Patient_Reports methods...
public static void main(String[] args) {
new Patient_Reports();
}
}
To address your main question, you would want to have some sort of generalized method you could call within your class like this:
public static void writePatientReports(int[] id, String[] patient,
String[] doctor, String[] surgery, double[] cost) {
BufferedWriter Student_file = new BufferedWriter(new FileWriter("patient.txt"));
for (i=0; i<=count; ++i)
{
//put "," between each data item in the file
Student_file.write(id[i] + "," + patient[i] + "," + doctor[i]+ "," + surgery[i] + ","+ cost[i]+ ",");
//write a new line in the file
Student_file.write("\n");
}//for loop
Student_file.close();
}
The reason you were getting errors is because you had no methods attached to Patient_Reports like write() or newLine(). And even if you had, you would have needlessly declared Student_file as a BufferedWriter object.
Further, you would do greatly in furthering your knowledge of Java and general OOP by reading Java Code Conventions
I am taking one csv comparing each line with every line of another csv to find matches.
I then need to add some elements from the second csv with some from the first and write it to a new file.
It works for the first lines of the csv then gets the ArrayIndexOutOfBoundsException.
I understand how arrays work and I've checked my csv and as far as I can see I'm not going out of bounds.
The first csv has 8 fields and contains all the customer info. The second has 15 fields and holds sales info on customers. the first 2 fields [0] and [1] are the same in both csv's if there is a record of sales.
If anyone could have a quick look I may be missing something stupid.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at excel.parse.ExcelParse.main(ExcelParse.java:61)
package excel.parse;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.File;
import java.io.IOException;
public class ExcelParse {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String csvFile2 = "\\\\SBS2011\\RedirectedFolders\\Josh.Hickinbotham\\My Documents\\Customer_Sales_Trends_Summary_by_Sales_Order_114641390.csv";
String csvFile1 = "\\\\SBS2011\\RedirectedFolders\\Josh.Hickinbotham\\My Documents\\All_Customers_Listing_for_Rep_114337469.csv";
BufferedReader br = null;
BufferedReader br2 = null;
BufferedWriter bw = null;
String line = "";
String line2 = "";
String csvSplitBy = ",";
Boolean match = false;
try {
br = new BufferedReader(new FileReader(csvFile1));
bw = new BufferedWriter(new FileWriter("\\\\SBS2011\\RedirectedFolders\\Josh.Hickinbotham\\My Documents\\newcsv.txt"));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] customer = line.split(csvSplitBy);
System.out.println(customer[1]);
br2 = new BufferedReader(new FileReader(csvFile2));
while ((line2 = br2.readLine()) != null) {
String[] file2 = line2.split(csvSplitBy);
if (customer[1].equals(file2[1])) {
match = true;
bw.write(customer[0] + "," + customer[1] + "," + customer[2] + "," + customer[3] + "," + customer[4] + ","
+ customer[5] + "," + customer[6] + "," + customer[7] + ","+ file2[2] +","+ file2[3] + "," + file2[4] + "," + file2[5] + ","
+ file2[6] + "," + file2[7] + "," + file2[8] + "," + file2[9] + "," + file2[10] + "," + file2[11] + "," + file2[12] + ","
+ file2[13] + "," + file2[14]+"\r\n");
System.out.println(":::MATCH " +customer[1]+" : "+file2[1]+" :::");
} else {
match = false;
}
}
if (match == false) {
bw.write(customer[0] + "," + customer[1] + "," + customer[2] + "," + customer[3] + "," + customer[4] + ","
+ customer[5] + "," + customer[6] + "," + customer[7] + "," + "," + "," + "," + "," + "," + "," + "," + "," + "," + ","
+ "," + ","+"\r\n");
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (br2 != null) {
try {
br2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
}
}
Try displaying what customer is before it goes into the if match == false.
May help to see what exactly you are dealing with. :)
What about a simple check on the bounds of the result of "split" ? if you dump your line at the point where the bounds are not OK, you will see the faulty input data....
I think the problem is in your file containing the csv. Maybe debug it and stop at the line where you get the exception to check what data customer contains.
But what I wanted to note:
I'm not sure your program is doing what it is supposed to do. When it finds a match it will print it out, but then keep going in the inner while loop and so at the end match will be false again and you print out the non-match.
So I think you want to put a break:
if (customer[1].equals(file2[1])) {
match = true;
bw.write(customer[0] + "," + customer[1] + "," + customer[2] + "," + customer[3] + "," + customer[4] + ","
+ customer[5] + "," + customer[6] + "," + customer[7] + ","+ file2[2] +","+ file2[3] + "," + file2[4] + "," + file2[5] + ","
+ file2[6] + "," + file2[7] + "," + file2[8] + "," + file2[9] + "," + file2[10] + "," + file2[11] + "," + file2[12] + ","
+ file2[13] + "," + file2[14]+"\r\n");
break;
}
I have a method getstaffinfo, which has 3 parameter (var_1, connection, filewriter fw), the var_1 value is read from a text file. So the method will be called as many times based on all the var_1 value passed from text file . approx ( 15000)
public static String getstaffid(String var_1, Connection connection,
FileWriter fw) throws SQLException, Exception
// Create a statement
{
String record = null;
ResultSet rs = null;
Statement stmt = connection.createStatement();
boolean empty = true;
try {
rs = stmt
.executeQuery("select username, firstname, lastname, middlename, street, city, stateorprovince, ziporpostalcode, countryorregion, fax, phone, extension, mobile, pager, title, primaryemail, secondaryemail, officename, description, comments, suspendeddate, userdata, employeeid, createuser, updateuser, createdate, updatedate, employeetype, servicedeskticketnumber, startdate, enddate, manager, businessapprover, technicalapprover, delegate, location, jobcodes, customproperty1, customproperty2, customproperty3, customproperty4, customproperty5, customproperty6, customproperty7, customproperty8, customproperty9, customproperty10 from globalusers where username = '"+ var_1 + "'");
ResultSetMetaData metaData = rs.getMetaData();
int columns = metaData.getColumnCount();
ArrayList<String> records = new ArrayList<String>();
while (rs.next()) {
empty = false;
//record = rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3) + " " + rs.getString(4) + " " + rs.getString(5) + " " + rs.getString(6) + " " + rs.getString(7) + " " + rs.getString(8) + " " + rs.getString(9) + " " + rs.getString(10) + " " + rs.getString(11) + " " + rs.getString(12) + " " + rs.getString(13) + " " + rs.getString(14) + " " + rs.getString(15) + " " + rs.getString(16) + " " + rs.getString(17) + " " + rs.getString(18) + " " + rs.getString(19) + " " + rs.getString(20) + " " + rs.getString(21) + " " + rs.getString(22) + " " + rs.getString(23) + " " + rs.getString(24) + " " + rs.getString(25) + " " + rs.getString(26) + " " + rs.getString(27) + " " + rs.getString(28) + " " + rs.getString(29) + " " + rs.getString(30) + " " + rs.getString(31) + " " + rs.getString(32) + " " + rs.getString(33) + " " + rs.getString(34) + " " + rs.getString(35) + " " + rs.getString(36) + " " + rs.getString(37) + " " + rs.getString(38) + " " + rs.getString(39) + " " + rs.getString(40) + " " + rs.getString(41) + " " + rs.getString(42) + " " + rs.getString(43) + " " + rs.getString(44) + " " + rs.getString(45) + " " + rs.getString(46) + " " + rs.getString(47);
for (int i = 1; i <= columns; i++) {
String value = rs.getString(i);
records.add(value);
}
for (int j = 0; j < records.size(); j++) {
record = records.get(j) + ",";
}
fw.append(record);
}
/*fw.append(rs.getString(1));
fw.append(',');
fw.append(rs.getString(2));
fw.append(',');
fw.append(rs.getString(3));
fw.append('\n'); */
} finally {
fw.flush();
rs.close();
stmt.close();
}
return record;
}
As you can see, am executing a query for 47 values, which could be null or it can have some value.
Then i iterate through this 47 column, take the value and store it to an array list. Then i iterate the array list and write all the values to the string record with comma seperated value. Which is written to a csv file.
But it does not work fine. Any inputs would be appreciated...
You may have already solved the problem. Just let you know that I tried to use your code just now and found the issue was here:
record = records.get(j) + ",";
You should use something like this:
record = record + records.get(j) + ",";
Also change String to StringBuffer will improve the performance.
You didn't write the exact problem you face, but there is one for sure: you never write a line break into the file, so all data gets in one line.
while (rs.next()) {
... // your code, with the for loops
fw.append(record); //writing out the line, from your code
fw.append("\r\n"); //line break -- add this line
} //this is the end of the "while(rs.next())" loop
...
I'm trying to display the information from a text file in a JTextArea I've created in a GUI. I've figured out how to get the info from the file to the JTextArea, but it's only grabbing the last line of the file. I need to display all of the lines. I keep changing the loop around, but can't figure this one out. Any help would be greatly appreciated. Here's a look at my code:
public TextArea() {
initComponents();
try {
FileReader one = new FileReader ("info.txt");
BufferedReader buf = new BufferedReader(one);
String line = "";
StringTokenizer st = null;
int lineNumber = 0, tokenNumber = 0;
//textArea.setText(line);
while ((line = buf.readLine()) != null) {
lineNumber++;
//break comma separated line using ","
st = new StringTokenizer(line, ",");
while (st.hasMoreTokens()) {
//display csv values
tokenNumber++;
line = ("Title: " + st.nextToken()
+ "\n" + "Make:" + st.nextToken()
+ "\n" + "Model:" + st.nextToken()
+ "\n" + "Year:" + st.nextToken()
+ "\n" + "Price:" + st.nextToken()
+ "\n" + "Notes:" + st.nextToken()
+ "\n" + "Details:" + st.nextToken()
+ "\n");
textArea.setText(line);
}
//reset token number
tokenNumber = 0;
//textArea.setText(line);
}
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(this, "File not found");
} catch (IOException e){
JOptionPane.showMessageDialog(this, "Data not read");
}
Look at your code:
while (st.hasMoreTokens()) {
//display csv values
tokenNumber++;
line = ("Title: " + st.nextToken()
+ "\n" + "Make:" + st.nextToken()
+ "\n" + "Model:" + st.nextToken()
+ "\n" + "Year:" + st.nextToken()
+ "\n" + "Price:" + st.nextToken()
+ "\n" + "Notes:" + st.nextToken()
+ "\n" + "Details:" + st.nextToken()
+ "\n");
textArea.setText(line);
}
Everytime you find a new token you set the textarea val to last token found.
So obviously text area will display only last line.
You can try something like:
textArea.setText(textArea.getText() + line);
I think You are overriding the line variable.
line+=...
Concatenate, and then set the value of the whole line concatenated outside the loop.
while (st.hasMoreTokens()) {
//display csv values
tokenNumber++;
line = line +"\n"+("Title: " + st.nextToken()
+ "\n" + "Make:" + st.nextToken()
+ "\n" + "Model:" + st.nextToken()
+ "\n" + "Year:" + st.nextToken()
+ "\n" + "Price:" + st.nextToken()
+ "\n" + "Notes:" + st.nextToken()
+ "\n" + "Details:" + st.nextToken()
+ "\n");
}
textArea.setText(line);