如何从一行中删除逗号并将其写入输出文件

时间:2019-03-27 16:38:34

标签: java

这是我的任务-编写一个程序,该程序读取一个文件并删除其中的所有逗号,然后将其写回到另一个文件中。它将显示在控制台窗口中,最后显示已删除的逗号数。 该程序需要:  提示用户输入要读取的文件名。  读取文件  将非逗号字符写入到output.txt中,包括所有空格。  读完输入文件后,将已删除的逗号总数写到控制台窗口。

例如,如果输入文件包含3 +,2 = 5m,7%,6 = 1 hello 然后output.txt文件应包含:

3 + 2 = 5m 7%6 = 1你好 并且控制台窗口应显示“ Removed 3逗号”。

现在我很难从输入文件中删除逗号,我想我应该在最后一个if语句下写一行。

试图弄清楚如何从输入文件中删除逗号

 package pkg4.pkg4.assignment;
import java.util.Scanner;
import java.io.*;

/**
 *
 * @author bambo
 */
public class Assignment {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
       Scanner keyboard = new Scanner(System.in); 
       System.out.println("What is the name of the inputfile?");
       String inputfile = keyboard.nextLine();
       File f = new File(inputfile);
       Scanner inputFile = new Scanner(f);

         System.out.println("Please enter the output file");
         String outputfile = keyboard.nextLine();


         FileWriter fw = new FileWriter(outputfile);
         PrintWriter pw = new PrintWriter(fw);


       int lineNumber=0;


       while(inputFile.hasNext());
        lineNumber++;
             int commacount = 0;

              String line = inputFile.nextLine();
             if (line.length () != 0)
                 commacount++;
              for(int i=0; i< line.length(); i++)
             {
                 if(line.charAt(i) == ',');
                 {
                     commacount++;
                 }

         pw.println("removed " + commacount + "commas");

    }

}
}

2 个答案:

答案 0 :(得分:1)

根据您对程序的要求,为简单起见,我建议您使用Java 8类。

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;

public class Assignment {

    public static void main(String[] args) throws IOException {
        String content = "";
        Scanner keyboard = new Scanner(System.in);
        System.out.println("What is the name of the input file?");
        String inputfile = keyboard.nextLine();
        content = new String(Files.readAllBytes(Paths.get(inputfile)));
        long total_numbers_of_char = content.chars().filter(num -> num == ',').count();
        System.out.println("Please enter the output file");
        content = content.replaceAll(",", "");
        String outputfile = keyboard.nextLine();
        Files.write(Paths.get(outputfile), content.getBytes());
        System.out.println("removed " + total_numbers_of_char + " commas");
        keyboard.close();
    }

}

答案 1 :(得分:0)

要在控制台上打印,您应该使用:

System.out.println("removed " + commacount + "commas");

要在输出文件中写入该行而不使用逗号:

pw.println(line.replaceAll(",",""));