public static void removeWord() {
try {
ArrayList list=new ArrayList();
BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(new File("wordlist.txt")))); 
String str=null; 
while((str=br.readLine())!=null) 

list.add(str);
}
System.out.println("Input which word you want to remove");
String b=in.nextLine();
    for(int i = 0 , len= list.size();i<len;++i){  
     if(list.get(i)==b){  
             list.remove(i);  
             --len;
             --i;
       }  
      }  
System.out.println("Remove successful");



} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
为什么运行删不掉txt中的对应内容

解决方案 »

  1.   

    在循环过程中  不能remove
      

  2.   


    if(list.get(i)==b){  首先你判断字符串相等不应该用==,应该用equals.
    还有就是你的文件是一行一行的读入,假设手工输入.感觉你上面的这些代码实际操作起来并不好.
      

  3.   

    是的比对字符串内容要用equals   str.equals(str1)
    至于实际操作我建议现在不要考虑那么多,各种情况都尝试,没试过永远不知道哪种方式最好。即使不好也要做下,因为以后你才能知道这种方式不好。
      

  4.   

    不知道是不是我理解得不对,如果你是说要删掉txt中的内容的话,这个代码是肯定不行的,毕竟你并没有将改变的内容重新写入txt
      

  5.   


    import java.util.ArrayList;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.StreamTokenizer;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.util.Scanner;public class RemoveWord{
    public static void main(String[] args)throws Exception{
    String fileName = "words.txt";
    ArrayList<String> words = getAllWordsFromFile(fileName);
    System.out.println("Words in " + fileName + " are:");
    showWords(words);
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Input the words you want to remove.(Split by blank space.)");
    //允许输入多个单词在同一个行,空格作为分隔符.
    String input = keyboard.nextLine();
    for(String word : input.split("\\s+")){
    removeWord(words,word);
    }
    showWords(words);
    } private static ArrayList<String> getAllWordsFromFile(String fileName)throws Exception{
    ArrayList<String> words = new ArrayList<String>();
    File wordsFile = new File(fileName);
    assert wordsFile.exists();
    StreamTokenizer tokenizer = new StreamTokenizer(
    new BufferedReader(
    new InputStreamReader(
     new FileInputStream(wordsFile))));
    int ttype = tokenizer.nextToken();
    while(ttype != StreamTokenizer.TT_EOF){
    if(ttype == StreamTokenizer.TT_NUMBER){
    words.add(tokenizer.nval + "");
    }else if(ttype == StreamTokenizer.TT_WORD){
    words.add(tokenizer.sval);
    }
    ttype = tokenizer.nextToken();
    }
    return words;
    } private static void removeWord(ArrayList<String> words,String word){
    while(words.remove(word)){
    //
    }
    //System.out.println("-----------------------");
    } private static void showWords(ArrayList<String> words){
    System.out.println("-------------------------");
    for(String word : words){
    System.out.println(word);
    }
    }
    }
      

  6.   

    那应该怎么改下呢?就是把txt文档读取到arraylist,然后通过remove删除其中的一项
      

  7.   

    然后把你remove以后的东西用write写回文件里面
      

  8.   

    然后把你remove以后的东西用write写回文件里面之后想了想自己发现这个问题了 谢谢各位
      

  9.   

    这不是只是remove list的数据吗?和删除txt文件有什么关系?
      

  10.   

    谁教你在遍历list的是执行remove的?你可以喷死他!!!
      

  11.   

    如果想在遍历时通过remove进行删除,通过for循环的快速遍历是不可以的,但是通过Iterator迭代器,是可以在迭代过程中直接删除的!!!!
      

  12.   

    那应该怎么改下呢?就是把txt文档读取到arraylist,然后通过remove删除其中的一项   如10楼所说,将已经改变了的list写回txt
      

  13.   

    ArrarList在遍历时是不能删除或添加元素的,会引起并发修改异常。如果实在想添加或者删除,就要使用列表迭代器(ListIteraror),这个可以修改元素。
      

  14.   

    下面代码应该能实现你的需求,唯一的bug就是没处理行与行之间衔接形成需要删除单词的情况import java.io.BufferedWriter;
    import java.io.BufferedReader;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.IOException;
    import java.io.PrintStream;public class Test{
    public static void main(String[] args){
    String word = "replace";
    Path from = Paths.get("src.txt");
    Path to = Paths.get("to.txt");
    try(BufferedReader reader = new BufferedReader(new InputStreamReader(Files.newInputStream(from)));
        PrintStream print = new PrintStream(Files.newOutputStream(to));){
    String content = null;
    System.setOut(print);
    while((content = reader.readLine()) != null){
    System.out.println(content.replaceAll("\\Q" + word + "\\E",""));
    } }catch(IOException e){
    e.printStackTrace();
    return;
    }
    }
    }
      

  15.   

    下面代码可以实现转折拼接.并且对于大文件来说.使用通道处理更加快速有效import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.nio.file.Path;
    import java.nio.ByteBuffer;
    import java.nio.CharBuffer;
    import java.nio.channels.FileChannel;
    import static java.nio.file.StandardOpenOption.*;
    import java.io.IOException;
    import java.util.EnumSet;
    import static java.nio.channels.FileChannel.MapMode.READ_WRITE;
    import java.nio.charset.Charset;
    import java.nio.MappedByteBuffer;public class Test{
    public static void main(String[] args){
    String wordToDelete = "";
    Path file = Paths.get(System.getProperty("user.dir")).resolve("Test.java");
    Path to = Paths.get(System.getProperty("user.dir")).resolve("to.txt");
    assert Files.exists(file);
    try{
    if(Files.exists(to)){
    Files.delete(to);
    }
    }catch(IOException e){
    e.printStackTrace();
    return;
    }
    try(FileChannel channel = (FileChannel) Files.newByteChannel(file,EnumSet.of(WRITE,READ));
    FileChannel toChannel = (FileChannel)Files.newByteChannel(to,EnumSet.of(WRITE,READ,CREATE));){

    ByteBuffer buf = ByteBuffer.allocate(50);
    CharBuffer cb = null;
    String content = null;
    Charset charset = Charset.defaultCharset();
    int lastIndex = 0;//用于找到最后一个wordToDelete的位置
    int lengthOfWord = wordToDelete.getBytes().length;
    int lengthOfContent = 0;
    while(channel.read(buf) != -1){
    buf.flip();
    cb = charset.decode(buf);
    content = cb.toString().replaceAll(System.lineSeparator(),"");
    //将读取到字节缓冲区用本地编码转成字符缓冲区,并且替换其中的换行符符号
    lengthOfContent = content.getBytes().length;

    lastIndex = content.lastIndexOf(wordToDelete);

    buf.clear(); if(lastIndex == -1){
    //说明没有找到对应要删除的内容.
    toChannel.write(ByteBuffer.wrap(content.getBytes(),0,lengthOfContent - lengthOfWord));

    buf.put(content.getBytes(),lengthOfContent - lengthOfWord,lengthOfWord);
    continue;
    } String subStr = content.substring(lastIndex + wordToDelete.length());
    content = content.replaceAll("\\Q" + wordToDelete + "\\E","");
    content = content.substring(0,content.length() - subStr.length());
    toChannel.write(ByteBuffer.wrap(content.getBytes()));
    buf.put(subStr.getBytes());
    }
    buf.flip();
    toChannel.write(buf);
    }catch(IOException e){
    e.printStackTrace();
    return;
    }
    }
    }
      

  16.   

    这样写方便 if(list.contains(str)){   list.remove(str);  }
      

  17.   

    删了一个size就变小了 比如 txt 原来在9,10号位置上你把9号位置的删掉了 原来在10号位置上的 序号就变成9号了
    而这个时候 i已经指向第10个了 你还怎么把原来10号位置上的数据删掉.....
      

  18.   

    高级for循环可以
      

  19.   


    for(int i = 0 , len= list.size();i<len;++i){  
         if(list.get(i)==b){  
                 list.remove(i);  
                 --len;
                 --i;
           }  
    }  在for循环里面手动操作循环变量,真的容易出错,像这种情况,你倒着循环(从列表末尾向开头循环)就好了。