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?

3
  • I don't see any arrays in your code. Commented Jul 29, 2015 at 14:55
  • To write file you could use FileWriter Commented Jul 29, 2015 at 14:56
  • In Java, \t represents single tab, \\t will be considered as string "\t" and NOT as a tab Commented Jul 29, 2015 at 16:40

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

4 Comments

yes this is correct, but you need to add the commons-apache-org jar.
That is true, thankfully it is not too complex. Highly recommended to download the Apache commons, lots of useful tools there.
I don't really understand this. I am a beginner at java.
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.
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)); 

4 Comments

Interesting code, what does arr[--size] do? Does Haven't ever seen syntax like that.
After removing one element from an array. I am making last element as NULL. Otherwise it will take the last value as it is.
Gotcha, thought so, why are we setting it to null though? That is sorta throwing me off.
@Anil arr[--size] = null; won't reduce the array length; it will just null out the last element of the array.
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++;
}

Comments

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();
}
}

4 Comments

This here comment is for the OP, note that he is using ArrayLists which are slightly different from regular arrays.
In Java, \t represents single tab, \\t will be considered as string "\t" and NOT as a tab
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: n00bunlimited.net/pastebin.php?show=64416
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.