日期:2014-05-20  浏览次数:20753 次

文件里的字符串删除问题
代码是这样的:
public class DelectEmp {

Scanner scan =new Scanner(System.in);

public void display() throws IOException{

String s;
while(true){
System.out.println("Employee 3 digit payroll number:");
s =scan.next();
try{
check.checkEmpCode(s);
} catch(Exception a){
System.out.println(a.getMessage()) ; 
continue;

break;
}
int count=0;
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("d:/record.txt")));
TreeMap<Integer,String> maps = new TreeMap<Integer,String>();
String line = null;
while((line=in.readLine())!=null){
int i = line.indexOf(":");
String str1 = line.substring(0,i);
int key = Integer.parseInt(str1);
String str2 = line.substring(i+1);
maps.put(key, str2);
count++;
}
 
for(int i = 0;i<=count;i++){
 
while(s==maps.get(i)){
maps.remove(i);
}
}
 

}}

我不会写了,就写到这里。卡了!!
文本里的字符串是一行一行的,一行是一个记录。
我想要实现的是:输入一个字符串,该字符串如是文本中某一行的子字符串,这删除它,文本中不存在该记录。

------解决方案--------------------
有一个比较假的实现方法。
你可以把文件里的记录都读到一个容器里。
然后删除,你想删除的记录。

然后,不以追加的方式(也就是重头开始写)的方法。
把容器里的东西都写到文件里。

不过,这种方法效率很2很2.
------解决方案--------------------
Java code
for(int i = count-1;i>=0;i--){//这里要从后开始删除,否则越删越少会造成i越界
if(maps.get(i).contains(s)){ //字符串比较要用equals,包含则用contains,而且这里是用if,而不是while
                             //另外你的get(i)的key是文件中读取的key吗?
maps.remove(i);
}
//最后把maps的内容输出到文件
in.close(); //首先关闭读取的文件流
PrintStream ps = new PrintStream(new FileOutputStream("d:/record.txt")); //打开输出流
for(Map.Entry<Integer, String> e : maps.entrySet()) {
    ps.println(e.getKey() + ":" + e.getValue());
}
ps.close();

------解决方案--------------------
你都写到这个地方了
那直接把你的maps写进文件不就行了吗
maps中要删除的数据,已经被你删除了啊

以非追加的方式写进文件,最后flush一下就行了。

你的这种写法好像只能这样写了吧。