Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从数组列表中删除字符串_Java - Fatal编程技术网

Java 从数组列表中删除字符串

Java 从数组列表中删除字符串,java,Java,我有一个数组列表,其中包含文本文件中的数据 文本文件的结构如下 1,2,Name,2,itemName 我的代码: String Cid = "1"; String Tid = "1"; //Help File iFile = new File("Records"); BufferedReader yourfile = new BufferedReader(new FileReader(iFile)); FileWriter writer = new FileWriter(iFile);

我有一个数组列表,其中包含文本文件中的数据

文本文件的结构如下

1,2,Name,2,itemName
我的代码:

String Cid = "1";
String Tid = "1";
//Help

File iFile = new File("Records");
BufferedReader yourfile = new BufferedReader(new FileReader(iFile));
FileWriter writer = new FileWriter(iFile);    
String dataRow = yourfile.readLine(); 

    while (dataRow != null){

        String[] dataArray = dataRow.split(",");

        if(Cid.equals(dataArray[1]) && Tid.equals(dataArray[3]))

            dataRow = yourfile.readLine(); 


        else{
            System.out.print(dataRow);
            writer.append(dataArray[0]+", ");
            writer.append(dataArray[1]+", ");
            writer.append(dataArray[2]+", ");
            writer.append(dataArray[3]+", ");
            writer.append(dataArray[4]);
            writer.append(System.getProperty("line.separator"));
            dataRow = yourfile.readLine(); 
        }
    }
    writer.flush();
    writer.close();
} 我希望能够删除名称id和项目id匹配的记录


我读到的所有关于从数组列表中删除项的内容都只涉及按项位置删除。任何帮助都将不胜感激

我认为您需要迭代数组列表中的每个元素,并为每个字符串创建一个java.util.StringTokenizer,使用“,”作为分隔符(我假设Name或itemName中没有逗号)

然后获取第2个和第4个标记并进行比较。如果匹配,则删除该项

如果使用从ArrayList末尾开始并移动到第0个元素的for循环,并在找到项时按索引删除它们,则可能最有效。

String Cid=“1”;
String Cid = "1";
String Tid = "1";

File iFile = new File("Records");
BufferedReader yourfile = new BufferedReader(new FileReader(iFile));
BufferedReader yourfile2 = new BufferedReader(new FileReader(iFile));

int total=0;
String rec=yourfile2.readLine(); 
while (rec != null){    // count total records (rows) 
    total++;
    rec=yourfile2.readLine(); 
}

String dataRow = yourfile.readLine(); 
String[] allTemp[]=new String[total][]; //create array of an array with size of the total record/row
int counter=0;

while (dataRow != null){

    String[] dataArray = dataRow.split(",");

    if(Cid.equals(dataArray[1]) && Tid.equals(dataArray[3]))
        dataRow = yourfile.readLine(); // skip current row if match found
    else{
        allTemp[counter]=dataArray; //if match not found, store the array into another array
        dataRow = yourfile.readLine();
        counter++; //index for allTemp array. note that counter start from zero and no increment if the current row is skipped
       }    
}
FileWriter writer = new FileWriter(iFile); //create new file which will replace the records file. here, all desired records from file already stored in allTemp array
for (String[] arr : allTemp){
     //check nullity of array inside the array(record). 
    if(arr!=null){
        for(int i=0;i<arr.length;i++){
            writer.append(arr[i]);
                if(i<arr.length-1) //add "," in every column except in the last column
                    writer.append(",");
        }
        writer.append(System.getProperty("line.separator"));
    }
}
writer.flush();
writer.close();
字符串Tid=“1”; 文件iFile=新文件(“记录”); BufferedReader yourfile=new BufferedReader(new FileReader(iFile)); BufferedReader yourfile2=新的BufferedReader(新文件读取器(iFile)); int-total=0; String rec=yourfile2.readLine(); while(rec!=null){//count总计记录(行) 总计++; rec=yourfile2.readLine(); } 字符串dataRow=yourfile.readLine(); 字符串[]allTemp[]=新字符串[总计][]//创建总记录/行大小的数组的数组 int计数器=0; while(dataRow!=null){ 字符串[]dataArray=dataRow.split(“,”); if(Cid.equals(dataArray[1])&Tid.equals(dataArray[3])) dataRow=yourfile.readLine();//如果找到匹配项,则跳过当前行 否则{ allTemp[counter]=dataArray;//如果未找到匹配项,请将该数组存储到另一个数组中 dataRow=yourfile.readLine(); 计数器+++;//allTemp数组的索引。请注意,如果跳过当前行,计数器从零开始,并且不递增 } } FileWriter writer=新的FileWriter(iFile)//创建将替换记录文件的新文件。这里,文件中所有需要的记录都已存储在allTemp数组中 对于(字符串[]arr:allTemp){ //检查数组(记录)内数组的空值。 如果(arr!=null){ 对于(int i=0;i
只要得到你想要的东西

你已经尝试过的东西?你的代码在哪里?用迭代器循环并删除它。但是你的文本文件结构对我来说毫无意义。现在有意义了吗?StringTokenizer是一个遗留类。应该使用
String.split()
谢谢,我会尝试一下,然后发回我建议的StringTokenizer,因为虽然它是“遗留”的,但并没有被弃用。这里的拆分是在一个简单的字符和字符串上进行的。拆分()将需要初始化/启动昂贵的正则表达式引擎。我认为StringTokenizer在这里可能更合适,尽管两者都可以使用。if(tokens[1]。equals(customerid)&&tokens[3]。equals(Itemid)){//我是否必须删除此行中的每个标记}您只需使用令牌比较来确定这是否是要删除的行。您不需要删除令牌本身。就像第5行有匹配的令牌一样,请从ArrayList中删除项目5。非常好的示例,感谢您花时间编写它。我将if语句更改为(Cid.equals(dataArray[1])&&Tid.equals(dataArray[3])因为这两个不匹配。如果我不清楚,很抱歉没有问题。希望这有帮助。是的,你应该更改if语句,因为我对你的txt文件结构不是很确定。我更改了它,但现在它只是删除了文本文件中的所有内容。要清楚,用户将在一行输入两个数字Cid和Tid,它们匹配在一起,我想要d删除那一行。很抱歉,我刚开始编程,只是想了解代码所做的一切。请确保您的文件名和您通过Filewriter创建的新文件不同。它将用空文件替换您的文件。是的,我更改了它。我将原始帖子更新为我更改的代码。(我不知道如何将代码作为注释发布)但在代码中,您必须授予777权限才能修改您正在读取的文件。。。
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class Neat {

    public static void main(String... string) throws FileNotFoundException {

        File file = new File("c:/AnyFile.txt");
        Scanner fileScanner = new Scanner(file);

        while (fileScanner.hasNextLine()) {
            String text = fileScanner.nextLine();
            String[] data = text.split(",");

            int recordId = Integer.parseInt(data[0]);
            int nameId = Integer.parseInt(data[1]);
            String name = data[2];
            int itemId = Integer.parseInt(data[3]);
            String itemName = data[4];

            if (nameId == itemId) {
                removeLineFromFile(file, text);
            }

        }

    }

    public static void removeLineFromFile(File file, String lineToRemove) {

        try {

            File inFile = file;

            if (!inFile.isFile()) {
                System.out.println("Parameter is not an existing file");
                return;
            }


            // Construct the new file that will later be renamed to the original
            // filename.
            File tempFile = new File(inFile.getAbsolutePath() + ".tmp");

            BufferedReader br = new BufferedReader(new FileReader(file));
            PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

            String line = null;

            // Read from the original file and write to the new
            // unless content matches data to be removed.
            while ((line = br.readLine()) != null) {

                if (!line.trim().equals(lineToRemove)) {

                    pw.println(line);
                    pw.flush();
                }
            }
            pw.close();
            br.close();

            // Delete the original file
            if (!inFile.delete()) {
                System.out.println("Could not delete file");
                return;
            }

            // Rename the new file to the filename the original file had.
            if (!tempFile.renameTo(inFile))
                System.out.println("Could not rename file");

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }


}