1

I am a beginner to Java. I have successfully exported user data input to a .txt file using a loop, but I would like to remove the last comma per every line of the file. I have tried using a delimiter but cannot get the replaceAll to successfully remove the last comma of every line.

My current method which exports data is this:

public void Quit()
                {   
                    System.out.println(ProjectList.get(0).ProjectName);
                    File fileObject = new File("results.txt");
                    CorrectInput = true;                
                    ShowMenu = false;                   //if ShowMenu is false, the program's menu will terminate
                    PrintWriter outputStream = null;
                    try
                    {
                        outputStream =
                             new PrintWriter(new FileOutputStream("results.txt"));
                    }
                    catch(FileNotFoundException e)
                    {
                        System.out.println("Error opening the file" +"results.txt");
                        System.exit(0);
                    }
                   for (int i=0; i<ProjectList.size(); i++){
                       outputStream.print(ProjectList.get(i).ProjectName+","+ ProjectList.get(i).NumberOfMember +","); //Project Name and Number of Members exported
                       for (int Membercount = 0; Membercount < ProjectList.get(i).NumberOfMember; Membercount ++) //For as long as the member count is less than the total number of members, the program will ask for the user input
                       {   

                           outputStream.print(ProjectList.get(i).TeamMember[Membercount]);
                           outputStream.print(",");
                           //END OF LIST OF MEMBERS
                       }

                       for (int CountingIndex = 0; CountingIndex < ProjectList.get(i).NumberOfMember; CountingIndex ++) //For as long as the member count is less than the total number of members, the program will ask for the user input
                       {   
                           outputStream.print(ProjectList.get(i).TeamMember[CountingIndex] + ",");
                           for (int CountedIndex = 0; CountedIndex < ProjectList.get(i).NumberOfMember; CountedIndex++) {


                               if(CountingIndex!=CountedIndex) { //new, adding csv format
                               outputStream.print(ProjectList.get(i).TeamMember[CountedIndex] + ",");
                               outputStream.print(ProjectList.get(i).Vote[CountingIndex][CountedIndex] + ",");

                               }


                           }

                       }
                       //for (int CountedIndex = 0; CountedIndex < ProjectList.get(i).NumberOfMember && CountingIndex != CountedIndex; CountedIndex++)


                       outputStream.println();
                   }  
                   outputStream.close();
                // read file data into a String
                // read file data into a String
                   String data = null;
                try {
                    data = new Scanner(new File("results.txt")).useDelimiter("\\Z").next();
                    data = data.replaceAll("(?m)\\,$", " ");
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


                    System.out.println("\tGoodbye. ");      
                    scan.close();

                }

An example .txt output looks like this:

PRO1,2,MEM1,MEM2,MEM1,MEM2,100,MEM2,MEM1,100,
PRO2,2,MEM3,MEM4,MEM3,MEM4,100,MEM4,MEM3,100,

But I would like the .txt/csv output to look like:

PRO1,2,MEM1,MEM2,MEM1,MEM2,100,MEM2,MEM1,100
PRO2,2,MEM3,MEM4,MEM3,MEM4,100,MEM4,MEM3,100

Should I move the try/catch statement for the scanner to a separate method? Thanks so much for your help.

carl_codes
  • 27
  • 8
  • 2
    How about you just use an if statement in the first loops to not put a comma when you're at the last column? – OneCricketeer Feb 27 '18 at 14:54
  • Hi, I did try that but ran into an issue as it's a two-dimensional array which is part of an array list, so the comma would be removed twice if I'm not mistaken. I would only want the comma to be removed once at the end of every line – carl_codes Feb 27 '18 at 14:56
  • 1
    More importantly, you're doing nothing with `data` String after you replace the comma – OneCricketeer Feb 27 '18 at 14:56
  • Ah, okay, so I should definitely re-print the data string – carl_codes Feb 27 '18 at 14:58
  • You could just join the collection on commas... https://stackoverflow.com/a/10850885/2308683 – OneCricketeer Feb 27 '18 at 15:00
  • `Arrays.asList(ProjectList.get(i).TeamMember)` gets you a list instead of an array... And please don't capitalize your variable names. Only do that for classes – OneCricketeer Feb 27 '18 at 15:02
  • Use next() of scanner class and count total character in a line and print total-1 – Nitin Feb 27 '18 at 16:31

3 Answers3

2

You can use substring to get string which is you looking for, I guess you are able to read line by line from text file:

this is the way you can get your desired String:

String s = "PRO1,2,MEM1,MEM2,MEM1,MEM2,100,MEM2,MEM1,100,";

        s = s.substring(0, s.length()-1);

        System.out.println(s);

Output: PRO1,2,MEM1,MEM2,MEM1,MEM2,100,MEM2,MEM1,100

Hope this will help.

Simmant
  • 1,477
  • 25
  • 39
  • Ok, thank you for your help! Instead of the println, would I need to use the PrintWriter class in a separate method to export the new string? – carl_codes Mar 01 '18 at 00:13
  • That is upto you, if method where you read the file and that logic is not too complex then you can write export logic there itself, but yeah best way to keep every thing separate so specific method will be good. – Simmant Mar 01 '18 at 12:06
1

You can read the txt file and, for each line readed as String, you can take all the String minus the last character with the String.subString method:

for ( line ) {
    String newLine = line.subString(0, line.length());
    .
    .
    .
}

Hope this help you, I could help you more but I have no time right now, sorry.

silversoul
  • 33
  • 8
  • If you are putting actual length in "endIndex" value then, it will make no change in string. It will remain same. – Simmant Feb 27 '18 at 17:41
0

One way it can be using commons file utils.

First you can split your file in lines.

List<String> lines = org.apache.commons.io.FileUtils.readLines(new File("file.txt"),"UTF-8");

Now, for each line you can take the string and check for the last index in which your character appears.

StringBuilder newFile = new StringBuilder();
    for(String line : lines){
        int endIndex = line.lastIndexOf(".");
        String newString = demo.substring(0, endIndex);
        //newString has the string without the last character.
        newFile.append(newString);
    }

org.apache.commons.io.FileUtils.writeStringToFile(new File("newFile.txt", newFile.toString(), "UTF-8");
OJVM
  • 1,403
  • 1
  • 25
  • 37
  • This is will make one extra loop for this task, and we can remove "," from last index with in the same loop where we iterating all text line from String. – Simmant Feb 27 '18 at 17:47