1

I have a text data like

name = abc

id = 123

Place = xyz

Details = some texts with two line



name = aaa

id = 54657

Place = dfd

Details = some texts with some lines

I need to place them in a table or csv and my output should look like

name       id     Place       Details    

abc        123     xyz         Some texts

dfd        54657   dfd         Some texts  

How can I do this with java?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • Parse the file, so you have the data grouped correctly, you can do this with a `List` of `List` (rows/columns) or even a `List` or `Map`, but I'd personally use a POJO of some kind, but that's me. Once you have it parsed, you can the format it, using maybe `String.format` to generate the required spacing between each column. As an [example](http://stackoverflow.com/questions/26229140/writing-data-to-text-file-in-table-format/26229246#26229246) and [example](http://stackoverflow.com/questions/28802139/how-to-align-my-results-to-look-like-columns/28802198#28802198) – MadProgrammer Jun 25 '15 at 06:57

3 Answers3

2

Code for the CSV version :) It reads the input file and create a CSV in the format you asked for:

try {
            BufferedReader sc = new BufferedReader(new FileReader("input2.txt"));

            ArrayList<String> name = new ArrayList<>();
            ArrayList<String> id = new ArrayList<>();
            ArrayList<String> place = new ArrayList<>();
            ArrayList<String> details = new ArrayList<>();

            String line = null;
            while ((line = sc.readLine()) !=null) {
                if (!line.trim().equals("")) {
                    System.out.println(line);
                    if (line.toLowerCase().contains("name")) {
                        name.add(line.split("=")[1].trim());
                    }
                    if (line.toLowerCase().contains("id")) {
                        id.add(line.split("=")[1].trim());
                    }
                    if (line.toLowerCase().contains("location")) {
                        place.add(line.split("=")[1].trim());
                    }
                    if (line.toLowerCase().contains("details")) {
                        details.add(line.split("=")[1].trim());
                    }
                }
            }

            PrintWriter pr = new PrintWriter(new File("out.csv"));
            pr.println("name;id;Place;Details;");
            for (int i = 0; i < name.size(); i++) {
                pr.println(name.get(i) + ";" + id.get(i) + ";" + place.get(i) + ";" + details.get(i) + ";");
            }
            pr.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

Sample file content it processes:

name = abinhav 
Location =Bangalore 
Id =613636064725610496 
Details = infoodnetwork: Q2 is up. You can still join the Megakitchens in India contest and grab some exciting vouchers. RT if you are enjoying… 

name = Mathi 
Location =Chennai 
Id =613636066474508289 
Details = i am the drifter Of course they can, but the BBC needs a daily negative story on India.
Ahs N
  • 8,233
  • 1
  • 28
  • 33
  • Thank you but when i try to run it shows output in console and it creates an empty file only?? how to over come it – Aravind Selvaraj Jun 25 '15 at 08:09
  • 1
    It is creating an empty file because it did not find the _input.txt_. `Scanner sc = new Scanner(new File("input.txt"));`. Modify the file path in the code if required, but ensure that Java is being able to load the file. – Ahs N Jun 25 '15 at 08:12
  • I think the input file is loaded because it prints the output in console.so something i have missed and more over when i print (name.get(i)) alone it creates a csv file by listing names in the names column and id place details has empty columns.When i print name id details and place all together i face this problem. – Aravind Selvaraj Jun 26 '15 at 04:34
  • 1
    I ran the code again and it works fine for me. The code does print the output to the console because of this line: `if (!line.trim().equals("")) { System.out.println(line);`... I would suggest you to replace `System.out.println(e.getMessage());` with `e.printStackTrace();` and run the code again. Does it throws any error in the console? – Ahs N Jun 26 '15 at 06:12
  • it does run for me only when i print (name.get(i) + ";" + id.get(i) ); but when i print the whole thing it shows some error in console like java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.rangeCheck(ArrayList.java:604) at java.util.ArrayList.get(ArrayList.java:382) at Transfer.main(Transfer.java:40) – Aravind Selvaraj Jun 26 '15 at 06:28
  • my input file sample is this one name : abinhav Location :Bangalore Id :613636064725610496 Details : infoodnetwork: Q2 is up. You can still join the Megakitchens in India contest and grab some exciting vouchers. RT if you are enjoying… name : Mathi Location :Chennai Id :613636066474508289 Details : i am the drifter Of course they can, but the BBC needs a daily negative story on India. – Aravind Selvaraj Jun 26 '15 at 06:31
  • 1
    Ofc it will throw you errors. The file structure you just provided is different compared to the initial sample you provided. Your second file uses ":" instead of "=" and you use "Location" instead of "Place" as initially indicated. Change the ":" to "=" to properly identify the categories in the file content you posted. I will update the code I posted before to work with those changes. – Ahs N Jun 26 '15 at 07:15
  • if there is any empty space will skip it automatically?? – Aravind Selvaraj Jun 26 '15 at 07:35
  • Yes it will. This piece of code handles it: `if (!line.trim().equals("")) {` – Ahs N Jun 26 '15 at 07:37
1
  1. Parse the text file with a Scanner (doc here)
  2. Create a DefaultTableModel (doc here). DefaultTableModel model = new DefaultTableModel(data, new String[]{"name","id","Place","Details"});, where data is a 2D String array with your data.
  3. Create a JTable (doc here) with the model you just created. JTable table = new JTable(model);
  4. Add the table to a JPanel, or JFrame, with a JScrollPane (if needed): panel.add(new JScrollPane(table));.
Eric Leibenguth
  • 4,167
  • 3
  • 24
  • 51
1

Reading from text file and writing to csv(comma seperated values) can be achieved using java io.

your logic should once write the headers to a text file with separator as comma and then read the corresponding values from the text may be use split("=") and append to the file with comma separator. You can create new files write the values and save the file with csv extension

try {
            BufferedReader bReader = new BufferedReader(new FileReader("input file"));
            String line = "";
            while ((line = bReader.readLine()) != null) {
                String[] strArray = line.split("=");
                // write this to file
                    System.out.println( strArray[1]);


                }
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
KDP
  • 1,481
  • 7
  • 13