Sunday, February 11, 2007

File I/O C# or Java Example

In Java, you can use the File object to perform basic file I/O operations, such as creating, opening, closing, reading, and writing a file. For example, you can use the methods of the File class to perform file I/O operations, such as using the createNewFile or delete methods of the File class to create or delete a file. You can use the BufferedReader and BufferedWriter classes to read and write the contents of files.

The following code example shows how to create a new file, delete a file, read text from a file, and write to a file.

Copy Code
// Java example code to create a new file
try
{
File file = new File("path and file_name");
boolean success = file.createNewFile();
}
catch (IOException e) { }

// Java example code to delete a file.
try
{
File file = new File("path and file_name");
boolean success = file.delete();
}
catch (IOException e) { }

// Java example code to read text from a file.
try
{
BufferedReader infile = new BufferedReader(new FileReader("path and file_name "));
String str;
while ((str = in.readLine()) != null)
{
process(str);
}
infile.close();
}
catch (IOException e)
{
// Exceptions ignored.
}

// Java example code to writing to a file.
try
{
BufferedWriter outfile =
new BufferedWriter(new FileWriter("path and file_name "));
outfile.write("a string");
outfile.close();
}
catch (IOException e) { }

C# File Operations Example

In C#, to perform a file I/O operation, you can use the same familiar basics of creating, opening, closing, reading, and writing using .NET Framework equivalent classes and methods. For example, you can use the methods of the File class of the .NET Framework to perform file I/O operations. For example, you can check for the existence of a file using the Exists method. You can use the Create method to create a file, optionally overwriting an existing file as illustrated in the following code example, and you can read and write using the FileStream class and the BufferedStream object.

The following code example shows how to delete a file, create a file, write to a file, and read from it.

C# Copy Code
// sample C# code for basic file I/O operations
// exceptions ignored for code simplicity

class TestFileIO
{
static void Main()
{
string fileName = "test.txt"; // a sample file name

// Delete the file if it exists.
if (System.IO.File.Exists(fileName))
{
System.IO.File.Delete(fileName);
}

// Create the file.
using (System.IO.FileStream fs = System.IO.File.Create(fileName, 1024))
{
// Add some information to the file.
byte[] info = new System.Text.UTF8Encoding(true).GetBytes("This is some text in the file.");
fs.Write(info, 0, info.Length);
}

// Open the file and read it back.
using (System.IO.StreamReader sr = System.IO.File.OpenText(fileName))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
System.Console.WriteLine(s);
}
}
}
}

No comments: