Search code examples
javafileoutputstreamstringbuffer

Stringbuffer issues


I wrote a code that enable users to open a text file in a text area and input new characters just like a text editor.It seems like there is a capacity issue when editing a large file and inputting large amount of charcater, the file doesn't get saved. I have tried StringBuffer stuff.ensureCapacity(10000);and still didn't work. I wonder if the problem is when saving to a file or when modifying within my text area? I have something like this:

  java.lang.StringBuffer text = new java.lang.StringBuffer();
  //some code here

  File myFile = new File(filename);
  DataInputStream dis = new DataInputStream(new FileInputStream (myFile));

    while((data = dis.readLine()) != null)
    {
      text.append(data+"\n");
    }

Solution

  • Some pointers.

    • You don't need to specify java.lang.
    • Don't use StringBuffer if you can use StringBuilder
    • Most importantly, don't mix text and binary as it will lead to confusion.

    If you want to read a whole file as a String I suggest using in Java 7

    Path path = FileSystems.getDefault().getPath("logs", "access.log");
    String text = new String(Files.readAllBytes(path), "UTF-8");
    

    or with Apache Commons IO FileUtils

    String text = FileUtils.readFileToString(new File(filename));