Use .NET IO (2)

zhaozj2021-02-17  49

Write characters to string

The following code example writes a number of characters starting from the character array to an existing string. Use StringWriter to complete this, as shown below.

[C #]

Using system;

Using system.io;

Using system.text;

Public Class Charstostr

{

Public static void main (string [] args)

{

// Create A Stringbuilder Object That Can the BE Modified.

Stringbuilder SB = New StringBuilder ("Some Number of Characters");

// define and initialize a character array from Which Characters

// Will Be Read InTo The StringBuilder Object.

Char [] b = {'', 't', 'o', '', 'w', 'r', 'I', 'T', 'E', '', 'T', 'O' , '.'};

// Create A StringWriter and attach it to the stringbuilder object.

StringWriter SW = New StringWriter (SB);

// Write Three Characters from The Array Into The Stringbuilder Object.

SW.WRITE (B, 0, 3);

// display the output.

Console.writeLine (SB);

// Close The StringWriter.

SW.CLOSE ();

}

}

This example illustrates the use of StringBuilder to modify an existing string. Note that this requires an additional using statement because the StringBuilder class is a member of the System.Text namespace. In addition, this is an example of directly creating a character array and initialize it, rather than defining a string and converts a string into a character array.

This code produces the following output:

Some Number of Characters To

Constitutional stream

The backup memory is a storage medium such as a disk or memory. Each different backup memory implements its own stream as the implementation of the Stream class. Each stream type is also read from its given backup memory and writes bytes to its reference memory. The stream connected to the backup memory is called a base stream. The constructor having the base stream has the parameters required to connect the stream to the backup memory. For example, FileStream has a constructor such as a specified path parameter (specify how to share files).

The design of the System.IO class provides a simplified stream. The base stream can be attached to one or more transfer streams that provide the desired function. The reader or writer can be attached to the end of the chain, so that you can easily read or write the desired type.

The following code example creates a FileStream object around the existing MyFile.txt to buffer myFile.txt. (Note that Buffest FileStreams by default.) Then, create streamReader to read characters in the filestream, and FileStream is passed to StreamReader as the constructor parameters as StreamReader. Readline is read until the PEEK finds no more characters.

[C #]

Using system;

Using system.io;

Public class compBuf {

Private const string file_name = "myfile.txt";

Public static void main (String [] args) {

IF (! file.exists (file_name)) {

Console.writeLine ("{0} does not exist!", File_name);

Return;

}

FILESTREAM FSIN = New fileStream (file_name, filemode.open,

FileAccess.read, Fileshare.Read;

// Create a Reader That Can Read Characters from The FileStream.

StreamReader SR = New StreamReader (fsin);

// while not at the end of the file, read lines from the file.

While (Sr.Peek ()> - 1) {

String Input = sr.readline ();

Console.writeLine (Input);

}

sr.close ();

}

}

The following code example creates a FileStream object around the existing MyFile.txt to buffer myFile.txt. (Note that by default, buffer FileStreams.) Then, create a binaryReader to read the byte in the filestream, and FileStream is passed to BinaryReader as a build function parameter as a BinaryReader. ReadByte is read until PeekChar finds no one another byte.

[C #]

Using system;

Using system.io;

Public class readbuf {

Private const string file_name = "myfile.txt";

Public static void main (String [] args) {

IF (! file.exists (file_name)) {

Console.writeLine ("{0} does not exist!", File_name);

Return;

}

FILESTREAM F = New fileStream (file_name, filemode.Open,

FileAccess.read, Fileshare.Read;

// Create a Reader That Can Read bytes from the filestream.

BinaryReader Sr = New BinaryReader (f);

// while not at the end of the file, read lines from the file.

While (Sr.Peekchar ()> - 1) {

BYTE INPUT = Sr.Readbyte ();

Console.writeLine (Input);

}

sr.close ();

}

}

Create a writer

The following code example creates a writer, the writer is a class that can get some types of data and convert it into a class array that can be passed to the stream.

[C #]

Using system;

Using system.io;

Public class mywriter {

PRIVATE stream s;

Public mywriter (stream stream) {

S = stream;

}

Public void writeouble (double mydata) {

Byte [] b = bitconverter.getbytes (mydata);

// GetBytes is a binary representation of a double data type.

S.Write (B, 0, B.Length);

}

Public void close () {

s.close ();

}

}

In this example, you have created a class with a constructor that has a stream parameter. From here, you can disclose any desired Write method. You must convert all the content written to Byte []. After you get Byte [], the Write method writes it.

Asynchronous file I / O

Synchronous I / O means that the method is blocked before the I / O operation is completed, and the method returns its data after the I / O operation is completed. Using asynchronous I / O, users can call BeginRead or BeGinWrite. The main thread can continue other work, later, the user will be able to process data. In addition, multiple I / O requests can be hang at the same time.

To get notifications when this data is available, you can call EndRead or endwrite to pass the IASYNCRESULT corresponding to the I / O request you sent. You can also provide a callback method that calls EndRead or endWrite to calculate how many bytes of reading or writing. When many I / O requests are hang, asynchronous I / O can provide better performance, but usually require some important adjustments to your application to work properly.

The Stream class supports mixing synchronous and asynchronous reading and writing on the same stream, regardless of whether the operating system is allowed. STREAM provides the default asynchronous reading and write operations in accordance with its synchronous implementation, and provides the implementation of the default synchronous read and write operations based on its asynchronous implementation.

When implementing the Stream derived class, you must provide implementation for one of the synchronous or asynchronous Read and Write methods. While it is allowed to rewrite Read and Write, and the default implementation of the asynchronous method (Beginread, Endread, BeginWrite and EndWrite) will work with the implementation of the synchronization method, this cannot provide the most effective performance. Similarly, if you provide an implementation of asynchronous methods, synchronous read and write methods will work normally, but if you specifically implement synchronization methods, performance is usually better. The default implementation of ReadByte and WritebyTe calls with a synchronization READ and WRITE method with an element byte array. When derived from the stream, if there is an internal byte buffer, it is highly recommended to rewrite these methods to access the internal buffer, which will be significantly improved.

Connecting to the stream weight of the backup memory or one of the asynchronous READ and WRITE methods to get the functionality of another method by default. If the flow does not support asynchronous or synchronous operations, the implementator only needs an appropriate method to trigger an exception.

The following example is an asynchronous implementation of a hypothetical image processor that is subsequently implemented. This code is used to execute the operation of the CPU resource on each file in the directory. For more information, see the ".NET Asynchronous Programming Model" topic in the .NET Framework Developer Specification.

[C #]

Using system;

Using system.io;

Using system.threading;

Using system.Runtime.InteropServices;

Public Class BulkimageProcasync

{

Public const string imagebasename = "tmpimage-";

Public const Int numimages = 200; public const INT numpixels = 512 * 512;

// processimage has a simple o (n) loop, and you can vary the number

// of Times You Repeat That Loop To Make The Application More CPU-Bound

// or more io-bound.

Public static int processimageRepeats = 20;

// Threads Must Decrement NumImagestofinish, and protect

// Their access to it through a mutex.

Public static int numimagestofinish = NumImages;

Public static object numimagesMutex = new object [0];

// WaitObject is Signalled When All Image Processing IS DONE.

Public static Object WaitObject = New Object [0];

Public Class ImageStateObject

{

PUBLIC BYTE [] PIXELS;

Public int imageum;

PUBLIC FILESTREAM FS;

}

Public static void makeimagefiles ()

{

INT SIDES = (int) Math.sqrt (Numpixels);

Console.write ("Making" NumImages " SIDES " X " SIDES " Images ... ");

Byte [] pixels = new byte [numpixels];

For (int i = 0; i

Pixels [i] = (byte) i;

For (int i = 0; i

{

FILESTREAM FS = New FileStream (ImageBaseName i ". TMP", FileMode.create,

FileAccess.write, Fileshare.none, 8192, False;

Fs.write (Pixels, 0, Pixels.length);

FlushfileBuffers (fs.handle);

fs.close ();

}

Console.writeline ("DONE.");

}

Public Static Void ReadinImageCallback (IasyncResult AsyncResult)

{

ImagestateObject State = (imagestateObject) asyncResult.asyncState;

//Console.writeline ("image " state.imagenum " Was Read

" (asyncResult.completedsynchronously": "Synchronously":

"asynchronously");

STREAM stream = state.fs; // (stream) asyncResult.asyncObject; int BytesRead = stream.endread (asyncResult);

IF (BytesRead! = Numpixels)

Throw New Exception ("in ReadinImageCallback, Got Wrong Number of Bytes

From the image! got: " bytesread);

ProcessImage (state.pixels, state.imagenum);

stream.close ();

// Now write out the image.

// USING Asynchronous Io Here APPEARS NOT to Be Best Practice. It ends up

// swamping the threadpool, Since The Threadpool Threads Are Blocked

// ON IO Requests That We've Just Queued to The Threadpool.

FILESTREAM FS = New FileStream (ImageBaseName State.imagenum ". Done",

Filemode.create, FileAccess.write, Fileshare.none, 4096, False;

fs.write (state.pixels, 0, numpixels);

fs.close ();

// this application model Uses Too Much Memory.

// Releaseing Memory As Soon As Possible Is A Good Idea, Especially Global

// state.

State.pixels = null;

// Record That An Image Is Done Now.

LOCK (NumImagesmutex)

{

NumImagestofinish -;

IF (NumImagestofinish == 0)

{

Monitor.enter (WaitObject);

Monitor.pulse; WaitObject);

Monitor.exit (WaitObject);

}

}

}

Public static void processimage (byte [] pixels, int imagenu

{

Console.WriteLine ("ProcessImage";

// Do some cpu-intensive operation on the image.

For (int i = 0; i

For (int J = 0; J

Pixels [J] = 1;

Console.writeline ("ProcessImage" ImageNum "DONE.");

}

Public Static Void ProcessImagesNbulk ()

{

Console.writeline ("Processing Images ...");

Long t0 = environment.tickcount;

NumImagestofinish = NumImages;

AsyncCallback readimageCallback = new asyncCallback (readinimageCallback); for (int i = 0; i

{

ImagestateObject State = new imagestateObject ();

State.pixels = new byte [numpixels];

State.imagenum = i;

// Very Large Items Are Read Only ONCE, SO You CAN Make THE

// Buffer on the file stream very small to save memory.

FILESTREAM FS = New FileStream (ImageBaseName i ". TMP",

Filemode.open, FileAccess.read, Fileshare.Read, 1, True;

State.fs = fs;

Fs.beginread (state.pixels, 0, numpixels, readimagecallback, state);

}

// determine WHETHER ALL IMAGES Are Done Being Processed.

// if NOT, Block Until All Are Finished.

Bool Mustblock = FALSE;

LOCK (NumImagesmutex)

{

IF (NumImagestofinish> 0)

Mustblock = true;

}

IF (MustBlock)

{

Console.writeline ("All worker threads are queued ... blocking unsy

Numleft: " NumImagestofinish);

Monitor.enter (WaitObject);

Monitor.wait (WaitObject);

Monitor.exit (WaitObject);

}

Long t1 = environment.tickcount;

Console.writeline ("Total Time Processing Images: {0} MS", (T1-T0));

}

Public static void cleanup ()

{

For (int i = 0; i

{

File.delete (ImageBaseName i ". TMP");

File.delete (ImageBaseName i ". DONE");

}

}

Public static void trytocleardiskcache ()

{

// Try to force all pending writes to disk, and clear the

// Disk cache of any data.

Byte [] bytes = new byte [100 * (1 << 20)];

For (int i = 0; i

BYTES [I] = 0;

BYTES = NULL;

Gc.collect ();

Thread.sleep (2000);

}

Public static void main (string [] args)

{

Console.writeline ("Bulk Image Processing Sample Application, USINGASYNC IO");

Console.Writeline ("Simulates Applying A Simple Transformation To

" NumImages " / "images /");

Console.Writeline ("(IE, Async FileStream & Threadpool Benchmark));

Console.Writeline ("Warning - this Test Requires" (Numpixels *

NumImages * 2) "Bytes of TMP Space");

IF (args.length == 1)

{

ProcessimageRepeats = int32.parse (Args [0]);

Console.writeline ("ProcessImage Inner loop -

" processimagerepection;

}

MakeImagefiles ();

Trytocleardiskcache ();

ProcessImagesNbulk ();

Cleanup ();

}

[DLLIMPORT ("kernel32", setLastError = true)]

Private static extern void flushfilebuffrs (intptr handle);

}

The following is a synchronization example of the same hypothesis.

[C #]

Using system;

Using system.io;

Using system.threading;

Using system.Runtime.InteropServices;

Public Class BulkimageProcsync

{

Public const string imagebasename = "tmpimage-";

Public const INT NumImages = 200;

Public const Int numpixels = 512 * 512;

// processimage has a simple o (n) loop, and you can vary the number

// of Times You Repeat That Loop To Make The Application More CPU-Bound OR

// More io-bound.

Public static int processimageRepeats = 20;

Public static void makeimagefiles ()

{

INT SIDES = (int) Math.sqrt (Numpixels);

Console.write ("Making" NumImages " SIDES " X " SIDES " Images ... ");

Byte [] pixels = new byte [numpixels];

For (int i = 0; i

Pixels [i] = (byte) i;

For (int i = 0; i

FileStream Fs = New Filestream (ImageBaseName i ". TMP", FileMode.create, FileAccess.write, Fileshare.none, 8192, False; fs.write (Pixels, 0, Pixels.length);

FlushfileBuffers (fs.handle);

fs.close ();

}

Console.writeline ("DONE.");

}

Public static void processimage (byte [] pixels, int imagenu

{

Console.WriteLine ("ProcessImage";

// do some cpu-intensive operation on the image

For (int i = 0; i

For (int J = 0; J

Pixels [J] = 1;

Console.writeline ("ProcessImage" ImageNum "DONE.");

}

Public Static Void ProcessImagesNbulk ()

{

Console.writeline ("Processing Images ...");

Long t0 = environment.tickcount;

Byte [] pixels = new byte [numpixels];

For (int i = 0; i

{

FILESTREAM INPUT = New FileStream (ImageBaseName i ". TMP", FileMode.Open,

FileAccess.read, Fileshare.Read, 4196, False;

Input.read (Pixels, 0, Numpixels);

INPUT.CLOSE ();

ProcessImage (Pixels, i);

FILESTREAM OUTPUT = New FileStream (ImageBaseName i ", DONE",

FileMode.create, FileAccess.write, Fileshare.none, 4196, False;

Output.write (Pixels, 0, Numpixels);

Output.close ();

}

Long t1 = environment.tickcount;

Console.writeline ("Total Time Processing Images: {0} MS", (T1-T0));

}

Public static void cleanup ()

{

For (int i = 0; i

{

File.delete (ImageBaseName i ". TMP");

File.delete (ImageBaseName i ". DONE");

}

}

Public static void trytocleardiskcache ()

{

Byte [] bytes = new byte [100 * (1 << 20)];

For (int i = 0; i

BYTES = NULL;

Gc.collect ();

Thread.sleep (2000);

}

Public static void main (string [] args)

{

Console.Writeline ("Bulk Image Processing Sample Application, Using Synchronous Io);

Console.writeline ("Simulates Applying A Simple Transformation To" NumImages "/" images / ");

Console.writeline ("(IE, Sync FileStream Benchmark));

Console.Writeline ("Warning - this Test Requires" (Numpixels * NumImages * 2) "BYTES OF TMP SPACE");

IF (args.length == 1) {

ProcessimageRepeats = int32.parse (Args [0]);

Console.WriteLine ("ProcessImage Inner Loop -" ProcessimageRepeats);

}

MakeImagefiles ();

Trytocleardiskcache ();

ProcessImagesNbulk ();

Cleanup ();

}

[DLLIMPORT ("kernel32", setLastError = true)]

Private static extern void flushfilebuffrs (intptr handle);

}

转载请注明原文地址:https://www.9cbs.com/read-28559.html

New Post(0)