cis 234: file input & output introduction. data storage is fundamental computers need to store...
TRANSCRIPT
CIS 234: File Input & Output
introduction
Data Storage Is Fundamental computers need to store data to
work with it memory (RAM) is fast but transient
lost when computer turned off storage devices are slow but
persistent diskette, hard drive, tape, CD-ROM,
DVD
Files on External Devices data
accounting data in "flat" files data in database files reports in word processor files images in graphics files
stored programs in files
Using Data Files with Java input/output classes in Java
import java.io.* file class constructor
File myData = new File("my.txt");// on same directory as class file
can also include file path"A:\\Project9\\my.txt" //note double slashes (escape char)
Files Have Properties name – file identifier + extension
mydata txt parent – drive + directory(s)
A:\My Documents\Project8\ path – parent + name
A:\My Documents\Project8\mydata.txt
File Properties - 2 readable – by the program writeable – can save data into it length – file size in bytes last modified – date last saved
File Class Methods canRead() – readable (true/false)
if (myData.canRead()) { some code}
canWrite() – can save to it (true/false)
length() – size lastModified() – date
File Class Methods - 2 getName()
String fn = myData.getName(); getPath() //if identified when created getParent() //if identified when created exists() – check to see if it's there
don't try to read if not there
File Organization "Hierarchy" a hierarchy is like an outline from top down:
file has records (1 or more), which have fields, which are made up of characters, which are made up of bits
OS Opens File sets up an area in memory to
receive data sends message to storage device finds location of file data on media
file allocation table in DOS may lock file so other programs
can't use it
OS Closes File may write unsaved data to medium frees up memory unlocks file
Input and Output Devices Java, C, etc. programs use
"standard" input and output devices
defaults input comes from keyboard output goes to screen
can override defaults e.g., send output to a file or printer
"Streams" two ways to deal with data
1 record at a time COBOL works with records
as a stream of data better for multiplatform systems Java and C work with streams
Creating an Output File two ways to associate file with an
output stream pass filename argument to
FileOutputStream constructor pass filename argument to File
constructor, then pass file object to FileOutputStream constructor
Read/write text files
Read – Input FileReader infile = new FileReader(“data.txt”); BufferedReader in = new BufferedReader(infile);
in.readLine(); // test end of data (inStr != null)
Write – output FileWriter outStream = new FileWriter(“data.txt”); PrintWriter out = new PrintWriter(outStream);
Out.println( “myData” + “|” + name);