Keep the delimiter at third position and rest of other split - java

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(",(?=(?:[^\"]\"[^\"]\")[^\"]$)")));

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();

want to print a particular cell's all the row values in excel in java

After getting a paticular item name and price I store it in excel sheet. Now I compare their price and get lowest price, but how can i print that lowest price all detail
my code is
public static void getMinPhonePrice() throws Exception {
File file = new File("C:\\Users\\user\\Desktop\\demo.xlsx");
FileInputStream fs = new FileInputStream(file);
XSSFWorkbook wb=new XSSFWorkbook(fs);
String min = wb.getSheetAt(0).getRow(0).getCell(1).getStringCellValue();
int value_min = Integer.parseInt(min.substring(1).replace(",", ""));
String getText = null;
XSSFSheet sh1= wb.getSheetAt(0);
for(int j=0;j<3;j++) {
getText = sh1.getRow(0).getCell(j).getStringCellValue();
System.out.println(getText);
}
for (int i = 1; i <=sh1.getLastRowNum(); i++) {
String c = sh1.getRow(i).getCell(1).getStringCellValue();
int value = Integer.parseInt(c.substring(1).replace(",", ""));
if(value < value_min) {
value_min=value;
for(int k=0;k<3;k++) {
getText = sh1.getRow(i).getCell(k).getStringCellValue();
System.out.println("minimum item detail"+getText);
}
}
}
}
}
but it not printing my minimum item detail
It seems like you don't need nested loop, and you need store other cell to string variable. Please try the bellow code.
File file = new File("phone_compare.xlsx");
FileInputStream fs = new FileInputStream(file);
XSSFWorkbook wb=new XSSFWorkbook(fs);
String min = wb.getSheetAt(0).getRow(0).getCell(1).getStringCellValue();
int value_min = Integer.parseInt(min.substring(1).replace(",", ""));
String getText = null;
String str1 = wb.getSheetAt(0).getRow(0).getCell(0).getStringCellValue();
String str2 = wb.getSheetAt(0).getRow(0).getCell(2).getStringCellValue();
getText = str1 +" " +value_min +" " +str2;
XSSFSheet sh1= wb.getSheetAt(0);
for (int i = 0; i <=sh1.getLastRowNum(); i++) {
String c = wb.getSheetAt(0).getRow(i).getCell(1).getStringCellValue();
int value = Integer.parseInt(c.substring(1).replace(",", ""));
if(value < value_min) {
value_min=value;
str1 = wb.getSheetAt(0).getRow(i).getCell(0).getStringCellValue();
str2 = wb.getSheetAt(0).getRow(i).getCell(2).getStringCellValue();
getText = str1 +" " +value_min +" " +str2;
}
}
System.out.println(getText);
}

How to read txt file that contains 2 documents written in a strange format?

this is how my txt file looks like: text file
What I did to read the ".i" and ".m" from the 2 documents
but i didn't get any result, that hash table result = null.
is there any another way to read this txt file?
while(br.ready())
{
String line = "" ; // br.readLine();
while ( (line= br.readLine()) != null)
{
//if line contains .I
if (line.contains(".I"))
{ //read the id and save it in id var
String[] result = line.split("\\s");
id = result [result.length - 1];
}
else if(line.contains(".M ")){
String[] result = line.split("\\s");
for(int i = 0; i < result.length; i++){
if(!ht.containsKey(result[i]))
{
ArrayList<tuple> temp = new ArrayList<tuple>();
int index = line.indexOf(result[i]);
tuple tmpTupl = new tuple(id+"", index+"");
temp.add(tmpTupl);
ht.put(result[i], temp);
}
}

In a single csv file, compare two lines for equality

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");
}

Write columns vertically instead of horizontally

I am using opencsv for getting values out of multiple csv sheets to write them into one csv sheets. This is what I am doing:
//reading all entries in a huge list
for (int j = 0; j < (fileList.size() - 740); j++) {
String csvFile = "C:\\" + fileList.get(j);
reader = new CSVReader(new FileReader(csvFile), ';');
hugeList = reader.readAll();
List<String[]> data = new ArrayList<String[]>();
List<String> tmp= new ArrayList<String>();
for(int m = 0; m < hugeList.size(); m++) {
String[] values = hugeList.get(m);
tmp.add(values[0]);
}
data.add(tmp.toArray(new String[0]));
writer.writeAll(data);
}
As you can see I am getting the file and write its content into a list(hugeList) and then mapping each value on a new data array which I am writing into my new sheet. The problem is I am getting the data in a row and not in a column:
How to write my data column-by-column? What is wrong in my algorithm?
I appreciate your reply!
What is wrong here is very simple: you must write a every entry as new line
E.g.: writer.writeNext(data);
See example below for more details
My Approach for a result in Column
for (int j = 0; j < fileList.size(); j++) {
String csvFile = readPath + fileList.get(j);
System.out.println("Read: " + csvFile);
reader = new CSVReader(new FileReader(csvFile), ';');
hugeList = reader.readAll();
String[] data = new String[1];
for (int m = 0; m < hugeList.size(); m++) {
String[] values = hugeList.get(m);
data[0] = values[0];
writer.writeNext(data);
}
}

Categories

Resources