需要编写一个程序,仅当文件的最后一个字符不是 int/number 时才删除它。这是我到目前为止所拥有的。
import java.io.*;
public class RemoveTurn{
public static void main(String[] arg){
try{
RandomAccessFile raf = new RandomAccessFile("test.txt", "rw");
long length = raf.length();
System.out.println("File Length="+raf.length());
//supposing that last line is of 8
raf.setLength(length - 1);
System.out.println("File Length="+raf.length());
raf.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
程序框架取自:happycodings.com
最佳答案
简单的想法是
- 以字符串形式读取文件。
- 检查 String 的最后一个字符,如果是数字则将其删除
- 将其写回文件
我绝对推荐您使用 apahe common IO ,你的生活将会变得非常轻松。
示例代码:
File f=new File("");
String s = FileUtils.readFileToString(f); //read the file using common IO
char c=s.charAt(s.length()-1); //get the last char of your string
if(!(c>='0' && c<='9')){ //if not number
s=s.substring(0,s.length()-1); //remove it
}
FileUtils.write(f, s); //write back to the file using common IO
编辑:
您不需要使用 Common IO,还有许多其他方法可以在 java 中读取
和写入
文件
关于java - 带附加文件的 If 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30782439/