0

I am trying to update a file with some value. But there are few junk values are also getting updated with the original content while saving. Using the below code.

public class WriteToFile{

    public static void main(String[] args){
        Path path = Paths.get("C:\\someFile.txt");
        String fileContent = new String("someText");
        if (Files.exists(path)) {
            final File filePath = new File("C:\\someFile.txt");
            try {
                FileUtils.writeFile(filePath,fileContent);
            } catch (final Exception e1) {
            // TODO What if writing to the state file fails??
            }
        }
     }

    public class FileUploadUtils {

     public static void writeFile(final File filePath, final Object 
     byteFileContent) {
         try (FileOutputStream fileOutputStream = new FileOutputStream(filePath);
              ObjectOutputStream out = new ObjectOutputStream(fileOutputStream)) {
              out.writeObject(byteFileContent);
         } catch (final IOException io) {
             io.printStackTrace();
         }
     }
   }

I am able to write the content to file also, but it is adding some junk characters also. like "’ t SomeText"

umesh
  • 312
  • 3
  • 4
  • 15
  • Possible duplicate of [writeUTF(String s) vs writeObject(String s)](https://stackoverflow.com/questions/19269688/writeutfstring-s-vs-writeobjectstring-s) – jhamon Apr 24 '18 at 09:51
  • Have you checked the encoding of your file and of your String you want to write, and if the junk characters are the BOM? – DamCx Apr 24 '18 at 09:52
  • You shouldn't be using an `ObjectOutputStream`, unless you want to specific Java serialization format used by it. Instead you need to use an `OutputStreamWriter`. – Mark Rotteveel Apr 24 '18 at 15:14

1 Answers1

0

The ObjectOutputStream seems to add some values while writing the data to the file. Why won't you directly use the FileOutputStream you created and pass the data as bytes ?

public static void main(String[] args) {

    Path path = Paths.get("C:\\someFile.txt");
    String fileContent = new String("someText");
    if (Files.exists(path)) {
        final File filePath = new File("C:\\someFile.txt");
        try {

            FileUploadUtils.writeFile(
                    filePath, fileContent.getBytes());
        } catch (final Exception e1) {
            // TODO What if writing to the state file fails??
        }
    }

}

public class FileUploadUtils {

public static void writeFile(final File filePath, final byte[] byteFileContent) {
    try (FileOutputStream fileOutputStream = new FileOutputStream(filePath)) {
        fileOutputStream.write(byteFileContent);
    } catch (final IOException io) {
        io.printStackTrace();
    }
}
}
Akhadra
  • 419
  • 3
  • 10