Easiest Way to Read from and Write to Files

Easiest way to read from and write to files

Use File.ReadAllText and File.WriteAllText.

MSDN example excerpt:

// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText);

...

// Open the file to read from.
string readText = File.ReadAllText(path);

How to read/write from/to a file using Go

Read/Write String from/to a File in Android

Hope this might be useful to you.

Write File:

private void writeToFile(String data,Context context) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}

Read File:

private String readFromFile(Context context) {

String ret = "";

try {
InputStream inputStream = context.openFileInput("config.txt");

if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();

while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append("\n").append(receiveString);
}

inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}

return ret;
}

Read and Write to File at the same time

Simply holding a FileStream open with exclusive (not shared) access will prevent other processes from accessing the file. This is the default when opening a file for read/write access.

You can 'overwrite' a file that you currently hold open by truncating it.

So:

using (var file = File.Open("storage.bin", FileMode.Open))
{
// read from the file

file.SetLength(0); // truncate the file

// write to the file
}

the method should be absolute safe, since the program should run on 2000 devices at the same time

Depending on how often you're writing to the file, this could become a chokepoint. You probably want to test this to see how scalable it is.

In addition, if one of the processes tries to operate on the file at the same time as another one, an IOException will be thrown. There isn't really a way to 'wait' on a file, so you probably want to coordinate file access in a more orderly fashion.



Related Topics



Leave a reply



Submit