删除文本文件的特定部分

时间:2015-01-28 19:03:49

标签: java java.util.scanner filereader

所以我有一个存储日期的程序。

这是计算文件中日期数的函数。

public static int getLineCount() throws FileNotFoundException {

    System.out.println("Line count called");
    int datenumber = 0;
    int attrnumber = 0;
    try {
        Scanner readLine = new Scanner(new FileReader(dates));
        readLine.useDelimiter("<>");
        while (readLine.hasNext()) {

            readLine.next();

            if (attrnumber == 3) {

                datenumber++;
                attrnumber = 0;

            } else {
                attrnumber++;
            }
        }
    } catch (IOException e) {
        System.out.print("Cannot read file!");
    }
    ;
    System.out.println("Line count is: " + datenumber);
    return datenumber;

}

这是文件的外观

14<>7<>2014<>sdfsdf<>14<>4<>2016<>asdas<>

格式为DAY&lt;&gt; MONTH&lt;&gt; YEAR&lt;&gt; NAME&lt;&gt;

假设我有3个日期存储,我想删除第二个日期,我怎么能完成这个?

我可以在这里使用相同的代码,但是一旦它到达我想要删除的位置,它会以某种方式删除数据吗?

我有

DAY1<>MONTH1<>YEAR1<>NAME1<>DAY2<>MONTH2<>YEAR2<>NAME2<>DAY3<>MONTH3<>YEAR3<>NAME3<>

我想要

DAY1<>MONTH1<>YEAR1<>NAME1<>DAY3<>MONTH3<>YEAR3<>NAME3<>

1 个答案:

答案 0 :(得分:0)

public static void main(String args[]){
    String str = "DAY1<>MONTH1<>YEAR1<>NAME1<>DAY2<>MONTH2<>YEAR2<>NAME2<>DAY3<>MONTH3<>YEAR3<>NAME3<>";
    System.out.println(remove(str, "<>", 4, 2));


}
/**
 * 
 * @param sentence your main sentence
 * @param delimeter delimeter which sentence contains like <>
 * @param range range of line, for this example as you can see each row contains 4 items, so its range is 4
 * @param removed_range, whing range is removed, for example 2 range etc
 * @return
 */
public static String remove(String sentence, String delimeter, int range, int removed_range){
    String str= "";
    ArrayList<String> items = new ArrayList<>();
    if(sentence.contains(delimeter)){
        items.addAll(Arrays.asList(sentence.split(delimeter)));
    }
    int cnt = 0;
    for(String item : items){
        if(cnt<range || cnt>= removed_range*range)
            str+=item+delimeter;
        cnt++;
    }

    return str;
}

结果:

DAY1<>MONTH1<>YEAR1<>NAME1<>DAY3<>MONTH3<>YEAR3<>NAME3<>