If statement with appending file

96 views Asked by At

Need to write a program that removes the last character of a file only if it's not an int / number. This what I have so far.

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

Program skeleton was taken from: happycodings.com

1

There are 1 answers

6
nafas On

the simple idea is

  1. To read the file as String.
  2. To check for the last char of the String , if number remove it
  3. To write it back to a file

I definitely recommend you using apahe common IO, your life will become very easy.

sample code:

    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

EDIT:

You don't need to use Common IO, there are many other ways of reading from and writing to a file in java