Search code examples
javafile-ioappendread-write

I want To append Some data in the File at specific location With the java Code


I want to append some data in a file the java code.

My file contains the following data:

#JSGF V1.0;

/**
 * JSGF Grammar for Hello World example
 */

grammar hello;

public <greet> = (ANKIT)|(BHAVIK)|(MONIL)|(JAY)|(HIREN)|(KRUTIKA)|(RIKIN)|(YAGNESH)|(KRISHNA);

and I want that whenever I append file that data come before the ; charachter

So if I add JAYA then it appends like following :

public <greet> = (ANKIT)|(BHAVIK)|(MONIL)|(JAY)|(HIREN)|(KRUTIKA)|(RIKIN)|(YAGNESH)|(KRISHNA)|(JAYA);

Please give me some proper suggession or sample code for this.

i had Done like this to achive this kind of stuff as follows..

try { File f = new File("E:\NEw_Workspace\Voice_recognition_modify\src\edu\cmu\sphinx\demo\helloworld\hello.gram"); RandomAccessFile raf = new RandomAccessFile(f, "rw");

                    // Read a character
                   // char ch = raf.readChar();

                    // Seek to end of file
                    raf.seek((f.length())-1);

                    // Append to the end
                    raf.writeChars("|(ASHISH);");
                    raf.close();
                } catch (IOException e) {
                }

but i am getting an the out put in file like follows: "A "then some square box image" then s "then some square box image" and so on


Solution

  • I had Done that With the Following Code ..Got success.

                   File f = new File("E:\\NEw_Workspace\\Voice_recognition_modify\\src\\edu\\cmu\\sphinx\\demo\\helloworld\\hello.gram");
                        RandomAccessFile raf = new RandomAccessFile(f, "rw");
    
                        // Read a character
                       // char ch = raf.readChar();
    
                        // Seek to end of file
                        raf.seek((f.length())-1);
    
                        // Append to the end
                        raf.write(("|(KARAN);").getBytes());
    
                        raf.close();
                    } catch (IOException e) {
                    }