venerdì 6 novembre 2009

Java: reading & writing files [ENG]

Since I can NEVER remember... here's the (very) quick and dirty code to read & write from text files.

private String readFile(String fileName)
  {
    if (fileName==null || "".equals(fileName))
    {
      return null;
    }
    try
    {
      FileReader reader = new FileReader(fileName);
      int next = -1;
      StringBuffer s = new StringBuffer();
      do 
      {
          next = reader.read();  
          if (next != -1) 
          {
              s.append((char)next); 
          }

      } while (next != -1);

      reader.close();  
      return s.toString();
    }
    catch (Exception e)
    {
      log(e.getMessage(), Project.MSG_ERR);
      throw new BuildException(e);
    }
  }
// --------------------------------------------------------

BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) 
{
   // process the line.
}
br.close();  

// --------------------------------------------------------
  private void writeFile(String content, String fileName)
  {
    try
    {
      FileWriter writer = new FileWriter(fileName, false);
      writer.write(content);
      writer.close();
    }
    catch (Exception e)
    {
      log(e.getMessage(), Project.MSG_ERR);
      throw new BuildException(e);
    }
  }

Nessun commento: