Tag Archives: stream

C#

Read and write files with stream in C#

fsutil
Very basic example how to read and write files. The util class is as following:

using System.IO;
using System.Text;

namespace Project.Dao
{
    public class FileSystemUtils
    {
        public static string ReadFile(string filePath, Encoding encoding)
        {
            using (var reader = new StreamReader(filePath, encoding))
            {
                return reader.ReadToEnd();
            }
        }

        public static void WriteFile(string filePath, string content, Encoding encoding)
        {
            using (var writer = new StreamWriter(filePath, false, encoding))
            {
                writer.Write(content);
            }
        }
    }
}

KISS paradigm enjoys.

Stream file download in a JSF managed bean

file_download

To output contents directly to browser in JSF 2.x use next method:

public static void downloadFile(String fileName, String content, String contentType) throws IOException {
  FacesContext fc = FacesContext.getCurrentInstance();
  ExternalContext ec = fc.getExternalContext();

  ec.responseReset();
  ec.setResponseContentType(contentType);
  ec.setResponseContentLength(content.length());
  ec.setResponseHeader("Content-Disposition", 
    "attachment; filename=\"" + fileName + "\"");

  OutputStream output = ec.getResponseOutputStream();
  output.write(content.getBytes());

  fc.responseComplete();
}

And example usage in action listener:

public void onSomeEvent(ActionEvent event) {
  try {
    StringBuilder result = new StringBuilder();
    result.append("ABC");
    downloadFile("file.csv", result.toString(), "text/csv");
  } catch (Exception e) {
    /* handle errors... */
  }
}

See also,
http://stackoverflow.com/questions/9391838/how-to-stream-a-file-download-in-a-jsf-backing-bean