Tag Archives: write

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.

Read and write text file in Java

Short for text file ex.

// Reading...
StringBuffer sb = new StringBuffer();
FileInputStream fis = null;
Reader reader = null;
try
{
	fis = new FileInputStream("in.txt");
	reader = new BufferedReader(new InputStreamReader(fis,"UTF-8"));
	char[] buffer = new char[1024];
	int read;
	while ((read = reader.read(buffer,0,buffer.length)) > 0)
		sb.append(buffer,0,read);
}
finally
{
	if (reader != null)
		reader.close();
	if (fis != null)
		fis.close();
}

// Processing...
String res = sb.toString() + "...OK!";

// Writing...
FileOutputStream fos = null;
Writer writer = null;
try
{
	fos = new FileOutputStream("out.txt");
	writer = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"));
	writer.write(res);
}
finally
{
	if (writer != null)
		writer.close();
	if (fos != null)
		fos.close();
}

Greate for me.

Write data file in Java


Snippet shows writing files to disk.

File outFile = new File("123.txt");
DataOutputStream dos = new DataOutputStream(new FileOutputStream(outFile));
dos.writeBytes("Some input string to save!");
dos.close();