latiasfan latiasfan - 1 year ago 68
Java Question

Editing an array from an imported file

So I am dealing with a problem where I am importing text from a notepad into java and am trying to put it into a csv file. I have successfully managed to do so, but now I need to remove info from each line of the array in the csv.

So to help visualize its something like this:

Name = Bob, Age = 42, FavColor = Blue
Name = Clarice, Age = 20, FavColor = Red
Name = John, Age = 34, FavColor = Green

And I want to remove the Name =, Age = and FavColor = from each part of the csv so that I only have the relevant data. Would look like this:

Bob, 42, Blue
Clarice, 20, Red
John, 34, Green

For further understanding of what I am doing my code thus far looks something like this:

public static void main(String[] args) throws IOException{
String file_name = "C:/Users/etc....";
PrintWriter pw = new PrintWriter(new File("test.csv"));
StringBuilder sb = new StringBuilder();

try {
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();


int i;
for(i = 0; i < aryLines.length; i++) {

System.out.println("CSV Written");
catch (IOException e) {
System.out.println( e.getMessage() );

The array is properly going through each line of the notepad info but I just am stumped on how to get the info removed. Any help would be appreciated. Thanks!

Answer Source

Try this:


Changed the regular expression to include word patterns with spaces:

import java.nio.charset.Charset;
import java.nio.file.*;
import java.util.*;

public class YourClass {

    public static void main(String[] args) {

        /** Path to the file being converted */
        String infile = "C:/Users/.../test.txt"; // Some absolute path
        /** Path to the destination output file */
        String outfile = "C:/Users/.../test.csv"; // Some absolute path

        try {           

            // Read all rows from the infile
            List<String> rows = Files.readAllLines(Paths.get(infile), Charset.forName("UTF-8"));
            // List of new rows to write to the outfile
            ArrayList<String> nrows = new ArrayList<String>();

            // Enumerate rows
            for (String row : rows) {
                // Remove any word followed by any number of spaces and
                // an equals sign followed by any number of spaces
                String nrow = row.replaceAll("[\\w\\s]+\\s*=\\s*", "");
                // Append edited row to new rows

            // Get file descriptor
            Path file = Paths.get(outfile);
            // Write rows to outfile
            Files.write(file, nrows, Charset.forName("UTF-8"));

            // Update G/TUI
            System.out.println("CSV Written");

        catch (IOException e) {
            // You should catch specific exceptions


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download