2

I want to remove the third value from an array I get from a text file. My text file looks like this:

item = 0    Dwarf_remains   The_body_of_a_Dwarf_savaged_by_Goblins. 0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
item = 1    Toolkit Good_for_repairing_a_broken_cannon. 0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
item = 2    Cannonball  Ammo_for_the_Dwarf_Cannon.  0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
item = 3    Nulodion's_notes    It's_a_Nulodion's_notes.    0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
item = 4    Ammo_mould  Used_to_make_cannon_ammunition. 0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
item = 5    Instruction_manual  An_old_note_book.   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0

Then I want to remove all these things:

The_body_of_a_Dwarf_savaged_by_Goblins.
Ammo_for_the_Dwarf_Cannon.
It's_a_Nulodion's_notes.
Used_to_make_cannon_ammunition.
An_old_note_book.

I am now using this code to get the array

import java.io.*;

public class Main {
    public static void main(String [] args) {

        // The name of the file to open.
        String fileName = "Items.cfg";

        // This will reference one line at a time
        String line = null;

        try {
            // FileReader reads text files in the default encoding.
            FileReader fileReader = 
                new FileReader(fileName);

            // Always wrap FileReader in BufferedReader.
            BufferedReader bufferedReader = 
                new BufferedReader(fileReader);

            while((line = bufferedReader.readLine()) != null) {
                String[] values = line.split("\\t");
                System.out.println(values[2]);
            }    

            // Always close files.
            bufferedReader.close();            
        }
        catch(FileNotFoundException ex) {
            System.out.println("Unable to open file '" + fileName + "'");                
        }
        catch(IOException ex) {
            System.out.println("Error reading file '"  + fileName + "'");                   
            // Or we could just do this: 
            // ex.printStackTrace();
        }
    }
}

When java removed all those is it possible to save the updated file in another file, like Items2.cfg or something?

RuuddR
  • 941
  • 4
  • 13
  • 25

4 Answers4

1

Similar to this here for example? I copied the answer over for easy access. Removing an element from an Array (Java)

array = ArrayUtils.removeElement(array, element)

http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/ArrayUtils.html

Community
  • 1
  • 1
SomeStudent
  • 2,856
  • 1
  • 22
  • 36
  • 1
    yes this is correct, but you need to add the commons-apache-org jar. – rhitz Jul 29 '15 at 15:15
  • That is true, thankfully it is not too complex. Highly recommended to download the Apache commons, lots of useful tools there. – SomeStudent Jul 29 '15 at 15:19
  • I don't really understand this. I am a beginner at java. – RuuddR Jul 29 '15 at 19:48
  • Apache Commons is a downloadable collection of new methods that are provided to you in the form of a .jar file. It contains many good extensions that java doesn't come with by default. I would highly recommend reading up about it. – SomeStudent Jul 29 '15 at 19:53
1

You can use System.arraycopy(src, srcPos, dest, destPos, length); method.

This method will not create new array. It will modify the existing array. See the below code:

String[] arr = {"Anil","Stack","Overflow","Reddy"};
  int size = arr.length;
  int index = 2;
  System.arraycopy(arr, index+1, arr, index, size-index-1); // modified the existing array, New Array will not create.
  arr[--size] = null;
  System.out.println(Arrays.toString(arr)); 
0

Here is the working code : Tested on your file.

Just change the file path.

Issue was '\t' which is tab instead of '\\t' which is a string '\t' and not a tab.

public static void main(String[] args) {

// The name of the file to open.
String fileName = "D:\\64416.txt";

// This will reference one line at a time
String line = null;

try {
    // FileReader reads text files in the default encoding.
    FileReader fileReader =
            new FileReader(fileName);

    // Always wrap FileReader in BufferedReader.
    BufferedReader bufferedReader =
            new BufferedReader(fileReader);

    FileWriter fw = new FileWriter("D:\\item2.txt"); //for Writing the file

    while ((line = bufferedReader.readLine()) != null) {
        String[] values = line.split("\t");
        List<String> list = new ArrayList<String>(Arrays.asList(values));
        list.remove(2);  // removing value from index 2
        for (String string : list) {
            fw.write(string + "\t"); //tab to be included
        }
        fw.write("\n");
        System.out.println(values[2]);
    }

    // Always close files.
    bufferedReader.close();
    fw.close();
} catch (FileNotFoundException ex) {
    System.out.println("Unable to open file '" + fileName + "'");
} catch (IOException ex) {
    System.out.println("Error reading file '" + fileName + "'");
    // Or we could just do this:
    // ex.printStackTrace();
}
}
rhitz
  • 1,892
  • 2
  • 21
  • 26
  • This here comment is for the OP, note that he is using ArrayLists which are slightly different from regular arrays. – SomeStudent Jul 29 '15 at 15:20
  • 1
    In Java, `\t` represents single `tab`, `\\t` will be considered as string `"\t"` and **NOT** as a **`tab`** – Shrinivas Shukla Jul 29 '15 at 16:39
  • Thank you, this worked. I only get an error `Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 1 at java.util.ArrayList.rangeCheck(Unknown Source) at java.util.ArrayList.remove(Unknown Source) at Main.main(Main.java:29)` and it happens after it removed some of these things. this is my whole file: http://www.n00bunlimited.net/pastebin.php?show=64416 – RuuddR Jul 29 '15 at 19:48
  • This means that you tried to access the second index while as your array size was only one, check to ensure you are not trying to access something that is out of bounds. Hence the exception. – SomeStudent Jul 29 '15 at 19:53
0

You know which element you're removing, so declare a new array whose length is 1 element smaller than your original array from the String.split()

Then using System.arraycopy(), copy the elements you want to keep from the original array into your new array.

public static void main(String[] args) throws Exception {
    String data = "item = 0\tDwarf_remains\tThe_body_of_a_Dwarf_savaged_by_Goblins.\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0\t0";

    System.out.println("Before: ");
    System.out.println(data);
    System.out.println();

    String[] pieces = data.split("\t");
    String[] newArray = new String[pieces.length - 1];
    // Copy index 0 & 1
    System.arraycopy(pieces, 0, newArray, 0, 2);
    // Skip index 2, and copy the rest
    System.arraycopy(pieces, 3, newArray, 2, pieces.length - 3);

    System.out.println("After: ");
    System.out.println(String.join("\t", newArray));
}

Results:

Before: 
item = 0    Dwarf_remains   The_body_of_a_Dwarf_savaged_by_Goblins. 0   0   0   0   0   0   0   0   0   0   0   0   0   0   0

After: 
item = 0    Dwarf_remains   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0

Otherwise you can use a for loop to copy the elements from the original array to your new array, skipping any element(s) that you don't want in the new array.

int newArrayIndex = 0;
for (int i = 0; i < pieces.length; i++) { 
    // Skip index 2       
    if (i == 2) {
        continue;
    }

    newArray[newArrayIndex] = pieces[i];
    newArrayIndex++;
}
Shar1er80
  • 9,001
  • 2
  • 20
  • 29