background image

Podstawy programowania 

(4)

dr Jerzy Bartoszek

jbartoszek@wskiz.edu

jerzy.bartoszek@put.poznan.p

l

background image

Obsługa plików

Przydatne składowe:
• przestrzeń nazw 

System.IO

 

• Klasy:

– FileStream
– StreamReader
– StreamWriter

 

– BinaryReader, 
– BinaryWriter

background image

Zapisywanie do pliku 

tekstowego

Dim 

fs

 As New System.IO.

FileStream

( _

"

file.txt

", FileMode.

Create

, _

 

FileAccess.

Write

)

Dim w As New 

StreamWriter

(

fs

)

w.BaseStream.

Seek

(0, SeekOrigin.End) 

w.

WriteLine

("Here is the file's text.") 

w.

Write

("Here is more file text." & _

ControlChars.CrLf)

w.WriteLine("And that's about it.") 
w.

Flush

() 

w.

Close

() 

background image

file.txt

fs

w

File

FileStrea
m

StreamWri
ter

background image

Odczytywanie z pliku 

tekstowego

Dim 

fs

 As New System.IO.

FileStream

( _

"

file.txt

", FileMode.

Open

, _

  FileAccess.

Read

)

Dim r As New 

StreamReader

(

fs

)

r.BaseStream.

Seek

(0, SeekOrigin.Begin) 

While r.

Peek()

 > -1 

Text &= r.

ReadLine

() & _

 ControlChars.CrLf 
End While

 

r.

Close

() 

background image

file.txt

fs

r

File

FileStrea
m

StreamRead
er

background image

Zapisywanie do pliku 

binarnego

Dim 

fs

 As New System.IO.

FileStream

( _

"data.txt", FileMode.

Create

, _

 

FileAccess.

Write

)

Dim w As New 

BinaryWriter

(

fs

)

w.BaseStream.

Seek

(0, SeekOrigin.End)

Dim LoopIndex As Int32
For LoopIndex = 0 To 19 

w.

Write

(LoopIndex) 

Next

 

w.

Flush

() 

w.

Close

() 

background image

Odczytywanie z pliku 

binarnego

Dim 

fs

 As New System.IO.

FileStream

( _

"data.dat", FileMode.

Open

, _

 

FileAccess.

Read

)

Dim r As New 

BinaryReader

(

fs

)

r.BaseStream.

Seek

(0, 

SeekOrigin.Begin) 
For LoopIndex = 0 To 19 

Text &= r.

ReadInt32

() & _ 

ControlChars.CrLf

 

 

r.

Close

() 


Document Outline