In a single csv file, compare two lines for equality - java

I have a single CSV file which contains many lines.
1shelf CSV file sample content:
#ManagementNode,SHELF-INFORMATION,NE_ID,RACK_ID,SHLEF_ID,STATUS,SHELF_TYPE,MAX_SLOT_NUMBER
ManagementNode,SHELF-INFORMATION,0005,0,0,,,13
#ManagementNode,BOARD-INFORMATION,NE_ID,RACK_ID,SHELF_ID,SLOT_ID,BOARD_NAME,ACTIVE_MODE,ADMIN_STATE,OPER_STATE,VERSION,SERIAL_NO,MANUFACTURER,MANUFACTURE_DATE
ManagementNode,BOARD-INFORMATION,0005,0,0,6,LEMA0,ACTIVE,UNLOCK,ENABLE,,S61F91571,XYZ,2014-09-03
2shelf CSV file sample content:
#ManagementNode,SHELF-INFORMATION,NE_ID,RACK_ID,SHLEF_ID,STATUS,SHELF_TYPE,MAX_SLOT_NUMBER
ManagementNode,SHELF-INFORMATION,0001,0,0,,,13
#ManagementNode,SHELF-INFORMATION,NE_ID,RACK_ID,SHLEF_ID,STATUS,SHELF_TYPE,MAX_SLOT_NUMBER
ManagementNode,SHELF-INFORMATION,0001,0,1,,,13
Please note that in the 2shelf file the header value of line 1 and line 3 is the same and also line 2 5th row value is 0 and line 5 5th row value is 1, this means it's a 2shelf file. The same is not true for 1shelf file.
I am new to Java, able to print required lines but dont know how to implement the compare logic to figure out 1shelf or 2shelf file.
BufferedReader in = new BufferedReader (new FileReader("C:\\Files\\1_2_Shelf\\Test.csv"));
String info = "";
int startLine = 4;
int endLine = 7;
for (int i = 0; i < startLine; i++) {
info = in.readLine();
}
for (int i = startLine; i < endLine + 1; i++) {
info = in.readLine();
System.out.println(info);
}
in.close();
}

Add the import shown below to the top of your class file.
Then use info.split(",") to break up the CSV string into fields in an array.
Then you will grab the 5th field of the array using field index = 4 (array element indexes starts at zero).
Sample code below, inserted into your original code:
import java.util.regex.Pattern; // NEW import to add at top of your file
...
// Some constants for identifying shelves
final int FIELD_SHELF_ID = 4;
final String SHELF1 = "0";
final String SHELF2 = "1";
BufferedReader in =
new BufferedReader (new FileReader("C:\\Files\\1_2_Shelf\\Test.csv"));
String info = "";
int startLine = 4;
int endLine = 7;
for (int i = 0; i < startLine; i++) {
info = in.readLine();
}
for (int i = startLine; i < endLine + 1; i++) {
info = in.readLine();
System.out.println(info);
String infoFields[] = info.split(",");
System.out.println("infoFields[FIELD_SHELF_ID] =
" + infoFields[FIELD_SHELF_ID]);
switch(infoFields[FIELD_SHELF_ID]) {
case SHELF1:
System.out.println("Found 1SHELF row"); break;
case SHELF2:
System.out.println("Found 2SHELF row"); break;
default:
System.out.println("Unknown shelf-type row"); break;
}
}
in.close();
If you are using an older version of Java, instead of the switch statement you can use if/else if/else as follows:
if (infoFields[FIELD_SHELF_ID].equals(SHELF1)) {
System.out.println("Found 1SHELF row");
}
else if (infoFields[FIELD_SHELF_ID].equals(SHELF2)) {
System.out.println("Found 2SHELF row");
}
else {
System.out.println("Unknown shelf-type row");
}

Related

How can i make my turn my text file to 40x40 matrix [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
In my code i need to read my text file and create a 40x40 matrix however my array only reads the first line Here is my code;
String worldData = "world.txt";
File worldFile = new File(worldData);
int[][] worldArray = new int[40][40];
Scanner scanner = new Scanner(worldFile);
while (scanner.hasNextLine()) {
String allText = scanner.nextLine();
String[] allLines = allText.split(";");
for (int i = 0; i < worldArray.length; i++) {
for (int j = 0; j < worldArray[0].length; j++) {
worldArray[i][j] = Integer.parseInt(allLines[0]);
}
}
I hope the in-line comment may give you some hints:
while (scanner.hasNextLine()) {
// you read a single line once in the while loop
String allText = scanner.nextLine();
String[] allLines = allText.split(";");
// here, for every new coming line, the for loop starts
// from array[0][0], therefore, it overwrites all the existing
// data. Thus, finally, you have only the last line in your array.
for (int i = 0; i < worldArray.length; i++) {
for (int j = 0; j < worldArray[0].length; j++) {
worldArray[i][j] = Integer.parseInt(allLines[0]);
}
}
Assuming that every line contains a row of the world matrix, the for-i loop should read exactly one line.
Scanner scanner = new Scanner(worldFile);
for (int i = 0; i < worldArray.length; i++) {
if (!scanner.hasNextLine()) {
throw new IllegalArgumentException("There are only " + i
+ " lines of the 40 needed.");
}
String line = scanner.nextLine();
String[] cells = line.split(";");
if (cells.length != 40) {
throw new IllegalArgumentException("There are " + i
+ " cells instead of the 40 needed.");
}
for (int j = 0; j < worldArray[0].length; j++) {
worldArray[i][j] = Integer.parseInt(cells[j]);
}
}
Alternatively you can do without a Scanner:
String worldData = "world.txt";
Path worldFile = Paths.get(worldData);
List<String> lines = Files.readAllLines(worldFile, StandardCharsets.UTF_8);
if (lines.size() < 40) {
throw new IllegalArgumentException("There are only "
+ lines.size()
+ " lines of the 40 needed.");
}
for (int i = 0; i < worldArray.length; i++) {
String line = lines.get(i);
String[] cells = line.split(";");
if (cells.length != 40) {
throw new IllegalArgumentException("There are " + i
+ " cells instead of the 40 needed.");
}
for (int j = 0; j < worldArray[0].length; j++) {
worldArray[i][j] = Integer.parseInt(cells[j]);
}
}
Other answers are good. Here you can try this to reduce loop operations and easily get integers from file without parsing String to Integer. Use delimiter with scanner object.
String worldData = "world.txt";
File worldFile = new File(worldData);
int[][] worldArray = new int[40][40];
int i = 0; // For index of worldArray
Scanner scanner = new Scanner(worldFile).useDelimiter("[\\n;]");
while(sc.hasNextInt()) {
wA[i/40][i%40] = sc.nextInt();
i++;
/* Since worldArray is a square matrix, you can keep
incrementing i and divide i by 40 to get rows index and i%40 to get column index thus simplifying the code.*/
}
you can use BufferedReader to read line by line from the file
BufferedReader br = new BufferedReader(new FileReader("world.txt"));
String line = null;
while((line=br.readLine()) != null) {
// process your line
}
br.close();

Keep the delimiter at third position and rest of other split

I am trying to split , (Comma) delimiter file where I need to skip , (Comma) at position three and rest of , (Comma) I can split.
My code:
String st;
BufferedReader Br = null;
FileOutputStream outFile1 = new FileOutputStream(
new File("C:\\DATA\\data.xls"));
Workbook book = new HSSFWorkbook();
File objFile = new File(
"C:\\DATA\\user.txt");
Br = new BufferedReader(new FileReader(objFile));
LineNumberReader lineNumberReader = new LineNumberReader(new FileReader(objFile));
lineNumberReader.skip(Long.MAX_VALUE);
int lines = lineNumberReader.getLineNumber();
Sheet sheet = book.createSheet("UserData");
System.out.println("Total Rows in the File : " +lines);
int line = 0;
while ((st = Br.readLine()) != null) {
String value = st.replace("\"", "");
arraylist = value.split(",");
Row row = null;
Cell cell = null;
row = sheet.createRow(line);
for (int i = 0; i < arraylist.length; i++) {
// System.out.println(arraylist[i]);
cell = row.createCell(i);
cell.setCellValue(arraylist[i]);
}
line++;
// System.out.println("Line: " + line);
}
book.write(outFile1);
outFile1.close();
Br.close();
How my txt file look:
"userid","Subscriberid ","HeadhouseFullname",
"167fgfg611","5904fds02","ABC, XYZ C"
"200fhskdhf","876fsgj25","ACD, NNP C"
"3893fjs956","502sgfgg3","ADC, KIO C"
"918shdfd71","1029gsg57","AED, JUI C"
Currently, when the code has been executed then it prints this file value:
userid Subscriberid HeadhouseFullname
167fgfg611 5904fds02 ABC XYZ C
200fhskdhf 876fsgj25 ACD NNP C
3893fjs956 502sgfgg3 ADC KIO C
918shdfd71 1029gsg57 AED JUI C
How it should be printed:
userid Subscriberid HeadhouseFullname
167fgfg611 5904fds02 ABC, XYZ C
200fhskdhf 876fsgj25 ACD, NNP C
3893fjs956 502sgfgg3 ADC, KIO C
918shdfd71 1029gsg57 AED, JUI C
Where you can notice that HeadhouseFullname column value is full name. For example "ABC, XYZ C" where I don't want to split full name by , (Comma) delimiter throughout the file. I want to keep it as it is "ABC, XYZ C".
Currently, it's splitting wherever it see , (Comma) delimiter.
I agree that you should be using a CSV lib as commented above, but if you want to keep going down your current path, try updating your split logic to be:
while ((st = Br.readLine()) != null) {
arraylist = st.split(",");
Row row = null;
Cell cell = null;
row = sheet.createRow(line);
for (int i = 0; i < arraylist.length; i++) {
// System.out.println(arraylist[i]);
cell = row.createCell(i);
cell.setCellValue(arraylist[i].replace("\"", ""));
}
line++;
//System.out.println("Line: " + line);
}
You could start splitting the line on " characters, i.e. st.split("\""). At this point, the resulting array would contain your entries of interest plus two additional kind of strings: empty and , character only.
String[] values = str.split("\"");
Once done that, you could iterate over the resulting array only considering and processing your entries as follows:
for (int valueIndex = 0; valueIndex < values.length; valueIndex++) {
if (values[valueIndex].length() > 0 && !values[valueIndex].equals(",")) {
// DO SOMETHING WITH values[valueIndex]...
}
}
So, considering the source code you posted, the while loop would change as follows:
while ((st = Br.readLine()) != null) {
String[] values = st.split("\"");
Row row = sheet.createRow(line++);
for (int valueIndex = 0, cellIndex = 0; valueIndex < values.length; valueIndex++) {
if (values[valueIndex].length() > 0 && !values[valueIndex].equals(",")) {
Cell cell = row.createCell(cellIndex++);
cell.setCellValue(values[valueIndex]);
}
}
}
Hope this helps!
Lorenzo
I added one additional loop with following updated code and now third column is populating combine with First name, last name and middle initial:
Here below is my updated code:
String st;
BufferedReader Br = null;
FileOutputStream outFile1 = new FileOutputStream(
new File("C:\\DATA\\data.xls"));
Workbook book = new HSSFWorkbook();
File objFile = new File(
"C:\\DATA\\user.txt");
Br = new BufferedReader(new FileReader(objFile));
LineNumberReader lineNumberReader = new LineNumberReader(new FileReader(objFile));
lineNumberReader.skip(Long.MAX_VALUE);
int lines = lineNumberReader.getLineNumber();
Sheet sheet = book.createSheet("UserData");
System.out.println("Total Rows in the File : " +lines);
int line = 0;
while ((st = Br.readLine()) != null) {
arraylist = st.split("," + "\"");
for (int i = 0; i < arraylist.length; i++) {
arraylist[i] = arraylist[i].replace("\"", "");
}
Row row = null;
Cell cell = null;
row = sheet.createRow(line);
for (int i = 0; i < arraylist.length; i++) {
// System.out.println(arraylist[i]);
cell = row.createCell(i);
cell.setCellValue(arraylist[i]);
}
line++;
// System.out.println("Line: " + line);
}
book.write(outFile1);
outFile1.close();
Br.close();
I have tried using regex and it helped for example
String txt = "0, 2, 23131312,\"This, is a message\", 1212312"; System.out.println(Arrays.toString(txt.split(",(?=(?:[^\"]\"[^\"]\")[^\"]$)")));

How do I get the function to print out a 2D array into two files in java?

My goal is to take a file with names and numbers, the first row will name the columns, the rows following will be the data. Column 0 will have the first name and 1 will have the last name which will be combined. Columns 2, 3, and 4 will contain 3 numbers that will be averaged together, columns 5 to 11 will also contain numbers that will be averaged together. This will be the test data:
first, last, #1, #2, #3, #4, #5, #6, #7, #8, #9, #10
Dan, Smith, 56, 58, 55, 66, 44, 78, 60.33, 52.33, 70.66, 44
Sam, Will, 77, 88, 55, 99, 77, 10, 62, 65, 59, 62
From here the two output files will contain the same information, the second will have the information spaced out in a neater fashion. What I want the out puts to be are:
name, exam score,hw score,min score
Dan Smith, 56.33, 62.66, 56.33
Sam Will, 73.33, 62, 62
This line will just be used for the second output file:
out.printf("%20s: %10.2f, %8.2f, %9.2f\r\n",name, average1, average2, smallestaverage);
My code is as follows, I tried to test and see if I could print out parts of the data using a for loop but would only receive the original values set for the two variables:
import java.util.Scanner;
import java.util.ArrayList;
import java.io.File;
import java.io.PrintWriter;
public class compute_grades {
public static void process_grades(String input_name, String csv_name, String pretty_name) {
String[][] data = read_spreadsheet(input_name);
String csvname = "csv_name.txt";
String pretty = "pretty_name.txt";
PrintWriter out = null;
try {
out = new PrintWriter(input_name);
} catch (Exception e) {
System.out.printf("Error: failed to open file %s.\n", input_name);
System.exit(0);
}
String first = "dog";
String last = "dat";
for (int i = 0; i < data.length; i++) {
first = data[i][0];
last = data[i][1];
}
System.out.println(first + last);
}
public static String[][] read_spreadsheet(String filename) {
ArrayList < String > lines = read_file(filename);
if (lines == null) {
return null;
}
int rows = lines.size();
String[][] result = new String[rows][];
for (int i = 0; i < rows; i++) {
String line = lines.get(i);
String[] values = line.split(",");
result[i] = values;
}
return result;
}
public static ArrayList < String > read_file(String filename) {
File temp = new File(filename);
Scanner input_file;
ArrayList < String > result = new ArrayList < String > ();
try {
input_file = new Scanner(temp);
} catch (Exception e) {
System.out.printf("Failed to open file %s\n", filename);
return result;
}
while (input_file.hasNextLine()) {
String line = input_file.nextLine();
result.add(line);
}
input_file.close();
return result;
}
public static void main(String[] args) {
Scanner in = new Scanner(System. in );
System.out.printf("Please enter the name of the input file: ");
String input_name = in .next();
System.out.printf("Please enter the name of the output CSV file: ");
String csv_name = in .next();
System.out.printf("Please enter the name of the output pretty-print file: ");
String pretty_name = in .next();
process_grades(input_name, csv_name, pretty_name);
System.out.printf("\n\nExiting...\n");
}
}
I don't get the difference between your two output files but I think your process Method should look like this:
public static void process_grades(String input_name, String csv_name, String pretty_name) {
String[][] data = read_spreadsheet(input_name);
PrintWriter out = null;
try {
out = new PrintWriter(csv_name);
} catch (Exception e) {
System.out.printf("Error: failed to open file %s.\n", input_name);
System.exit(0);
}
// print header
out.printf("name, exam score,hw score,min score\r\n");
// go throu all the other rows
for (int row = 1; row < data.length; row++) {
// get Name
String name = data[row][0] + " "+ data[row][1];
// avg the next three cols
double average1 = 0;
for(int col = 2; col < 5; col++)
average1 += Double.parseDouble(data[row][col].trim());
average1 /= 3;
// avg the next seven cols
double average2 = 0;
for(int col = 5; col < 12; col++)
average2 += Double.parseDouble(data[row][col].trim());
average2 /= 7;
//get min score
double smallestaverage = Math.min(average1,average2);
// print the content
out.printf("%20s: %10.2f, %8.2f, %9.2f\r\n",name, average1, average2, smallestaverage);
}
// flush the output and close the writer
out.flush();
out.close();
}

Failed to looping in a jtable in JCCD API

I have build code clone application, that using JCCD API that impelemnted ANTLR. To show the code clone, I am using a jtable. This is my screenshot Application : https://docs.google.com/file/d/0B_Rg--NnjJccMERpaTNidzR3cFE/edit?usp=sharing
Okey, from the following screenshot above, I was success to compare one file to another one file. The problem is when I am compare a file to two or more files. The tables just give me the last suspect of code clone.
But, in my netbeans output console, I was success that showed in this link : https://drive.google.com/file/d/0B_Rg--NnjJccWWdVTjdZc1R1bWc/edit?usp=sharing
How can I showed the right output console one to more files to my jTable ?
This is My code :
public static void printSimilarityGroups(final SimilarityGroupManager groupContainer) {
SimilarityGroup[] simGroups = groupContainer.getSimilarityGroups(); // output similarity groups
DefaultTableModel model = (DefaultTableModel) Main_Menu.jTable1.getModel();
model.setRowCount(0);
List<final_tugas_akhir.Report> theListData = new ArrayList<Report>();
if (null == simGroups) {
simGroups = new SimilarityGroup[0];
}
if ((null != simGroups) && (0 < simGroups.length)) {
for (int i = 0; i < simGroups.length; i++) {
final ASourceUnit[] nodes = simGroups[i].getNodes();
System.out.println("");
System.out.println("Similarity Group " + simGroups[i].getGroupId());
for (int j = 0; j < nodes.length; j++) {
final SourceUnitPosistion minPos = getFirstNodePosition((ANode) nodes[j]);
final SourceUnitPosistion maxPos = getLastNodePosition((ANode) nodes[j]);
ANode fileNode = (ANode) nodes[j];
while (fileNode.getTipe() != TipeNode.FILE.getTipe()) {
fileNode = fileNode.getParent();
}
final_tugas_akhir.Report theResult = new final_tugas_akhir.Report(); //final_tugas_akhir.Report() is a class that contain getter and setter
//Mixing the Line
StringBuilder sb = new StringBuilder();
StringBuilder append = sb.append(minPos.getBaris()).append("."); // get the row
sb.append(minPos.getKarakter()).append(" - "); //get Character
StringBuilder append1 = sb.append(maxPos.getBaris()).append(".");// get row
sb.append(maxPos.getKarakter()); get the character
theResult.setSimiliaritygroup(simGroups[i].getGroupId()); //Similiarity Group
theResult.setId(nodes[j].getId()); //setter similiarity id on token
theResult.setIndikasi(nodes[j].getText()); // setter Kind of Similairity
theResult.setFileutama(fileNode.getText()); //Files name
theResult.setLine(sb.toString());
theListData.add(theResult);
}
}
for (Report report : theListData) {
//test for the console
System.out.print(report.getSimiliaritygroup() + " ");
System.out.print(report.getId() + " ");
System.out.print(report.getIndikasi() + " ");
System.out.print(report.getFileutama() + " ");
System.out.print(report.getLine() + "\n");
//for table that failed
model.addRow(new Object[]{
report.getSimiliaritygroup(),
report.getId(),
report.getIndikasi(),
report.getFileutama(),
report.getLine()});
}
} else {
System.out.println("No similar nodes found.");
}
}
Thank you so much...

How to step reader.readLine() in two for cycles ?

I am reading data from a txt file. I want to create new objects from every ten lines and "." indicates that the current object doesn't have any more data lines (I work with two types of object("Nemfuggetlen" and "fuggetlen"), "fuggetlen" has 9 and "Nemfuggetlen" has 7 lines, "." separates their data lines).
The problem is: when I read two "Nemfuggetlen" objects in a row, it works fine, but if I read "fuggetlen" after "Nemfuggetlen" it makes "-------" to the next object first data lines, when it shouldn't. For "Nemfuggetlen" object it should fill the last 3 lines of "adatok" string array with "-------" and step to the next object.
int sorokszama = 0;
input.mark(300);
while((s = input.readLine()) !=null){
sorokszama++;
System.out.println("Sorok szama : " + sorokszama);
input.reset();
for(int h = 0; h < sorokszama/10; h++){
for(int i = 0;(s = input.readLine()) !=null; i++) {
if(i < 10){
if(!(".".equals(s))) {
adatok[i] = s;
System.out.println(adatok[i]);
}
else {
adatok[i] = "-------";
System.out.println(adatok[i]);
break;
}
}
}
if("Ferfi".equals(adatok[2])){
nem = true;
}
else {
nem = false;
}
if("Van".equals(adatok[4])){
tamogato = true;
}
else{
tamogato = false;
}
if("-------".equals(adatok[7])){ //A kepviselo nem fuggetlen
k = new Nemfuggetlen(adatok[0], Integer.parseInt(adatok[1]), nem, adatok[4], new Kerulet (Integer.parseInt(adatok[5])), adatok[6]);
}
if("-------".equals(adatok[9])){ // A kepviselo fuggetlen
k = new Fuggetlen(adatok[0], Integer.parseInt(adatok[1]), nem, adatok[4], new Kerulet (Integer.parseInt(adatok[5])),tamogato, adatok[7], Integer.parseInt(adatok[8]));
}
kepviselok.add(k);
//System.out.println(kepviselok.get(0));
}
System.out.println("Kepviselok szama : " + sorokszama/10);
for(int i = 0; i < kepviselok.size(); i++) {
System.out.println((i+1) + ". tag : " + kepviselok.get(i));
}
input.close();

Categories

Resources