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?

1
  • 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 and example Commented Jun 25, 2015 at 6:57

3 Answers 3

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.
Sign up to request clarification or add additional context in comments.

9 Comments

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
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.
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.
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?
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.
|
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();
        }

1 Comment

getting an exception any idea how to handle it ?? java.lang.ArrayIndexOutOfBoundsException: 1 at Table.main(Table.java:14)
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));.

3 Comments

Thank you Will try and let you know :)
Sorry, the answer is not relevant as you don't need to show the data in a GUI. I leave the post though, as it may be useful to users understanding the title of the question as I did.
Oh okay I am new to it .Is there any other easy way with simple logics or codes??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.