在Java中删除数组中的条目

时间:2013-11-05 08:42:56

标签: java arrays loops printwriter

它比标题更复杂。 我正在使用循环写入文件,然后我将使用Scanner类和File类读取文件,之后我想将类读取的数据存储到数组中。 之后,用户将选择要删除的数组中的一个条目。

我知道如何声明数组和所有内容,但我坚持如何将文件的信息存储到数组中,然后删除一个条目(例如L102),这里是代码: 请运行代码后,将Pats文件复制到C:目录。

package lecture;
import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;

public class Lecture{

public static void main (String args[]) throws IOException
{

    PrintWriter f0 = new PrintWriter(new FileWriter("Pats.txt"));
    int n=0;

    while(n<15)
        {

        int L=1;
        n++;
        f0.print("L"+L+"0"+n+"  ");
        System.out.println("L"+L +" "+n);

        L=L+1;
        f0.print("L"+L+"0"+n+"  ");
        System.out.println("L"+L +" "+n);

        L=L+1;
        f0.print("L"+L+"0"+n+"  ");
        System.out.println("L"+L +" "+n);

        }

        File Plots = new File("C:\\Pats.txt");
        Scanner ReadFile = new Scanner(Plots);
            while(ReadFile.hasNext())
            {

                String str = ReadFile.nextLine();
                System.out.println(str);

            }
         ReadFile.close();



f0.close();
}
}

2 个答案:

答案 0 :(得分:0)

我不确定你的思路是否最佳,但在你的while循环中,你可以有以下几点:

while(ReadFile.hasNext())
{

     String str = ReadFile.nextLine();
     System.out.println(str);
     lines.add(str);
}

lines是在循环之外声明的ArrayList

要从中删除,您只需要让用户选择index,然后执行lines.remove(index)或让用户选择String,在这种情况下您可以执行此操作lines.remove(string)

答案 1 :(得分:0)

正如我理解您的问题,您希望将数据从文件读取到数组,然后从该数组中删除任何元素。所以你可以按照以下方式进行,

  • 将数据读取到数组

逐行将文件中的数据读入StringBuilder

File file = new File("Pats.txt");
Scanner sc = new Scanner(file);
StringBuilder sb = new StringBuilder();
while (sc.hasNextLine()) {
    sb.append(sc.nextLine());
}
sc.close();

拆分数据并将结果分配给数组

final String readStr = sb.toString();
String[] array = readStr.split("  ");
  • 从数组中删除元素

由于我们无法调整java数组的大小,但您仍想使用数组,因此可以使用Apache CommonsLang component。从here下载jar。请参阅javadoc here

array = ArrayUtils.removeElement(array, "L102");