Java Files (File I/O)
-
Upload
abel-dunlap -
Category
Documents
-
view
32 -
download
0
description
Transcript of Java Files (File I/O)
Java Files (File I/O)IST 256
Application Programming for Information SystemsXiaozhong Liu
Yatish Hegde
https://xliu12.mysite.syr.edu/
File I/O
Hard Disk(Secondary Memory)
Memory(Primary Memory)
Read
Write
Process
I/O Streams
Input Stream
Output Stream
Default input/output streams
Java - Streams
JAVA provides 2 types of streams
Text streams - containing ‘characters‘
I ‘ M A S T R I N G \nProgram Device
Binary Streams - containing 8 – bit information
01101001Program Device11101101 00000000
Reading and Writing Files
Create a stream object and associate it with a disk-file
Give the stream object the desired functionality
while there is more information read(write) next data from(to) the stream
close the stream
public static void readFile(){
BufferedReader ins = new BufferedReader(new FileReader(“test.txt”));while(ins.ready()){
String s = ins.readLine();System.out.println(s);
}ins.close();
}
Reading Files
Important: Place the code insideTry{…}Catch{….}Wherever necessary
import java.io.*;
public static void writeFile(){
String s = “I love programming”;BufferedWriter outs = new BufferedWriter(new FileWriter(“test_out.txt”));outs.write(s);
}outs.close();
Writing File
Important: Place the code insideTry{…}Catch{….}Wherever necessary
import java.io.*;
Public static void readFile(){
BufferedReader ins = new BufferedReader(new FileReader(“test.txt”));Scanner scanner = new Scanner(ins);while(scanner.hasNext()){
System.out.println(scanner.next());}scanner.close();
}
Reading tokens from file
Important: Place the code insideTry{…}Catch{….}Wherever necessary
import java.io.*;Import java.util.Scanner;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{JFileChooser fc = new JFileChooser();
if(fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String inputFilePath = file.getAbsolutePath().toString(); jTextField1.setText(inputFilePath); } }
Browse Files using GUI
Try this for fun In a notepad, type few sentences and save the
file as test.txt. Write a Java program to read the text in test.txt and write that to file test_out.txt.
In a notepad, type 10 numbers (any numbers in the range 0 to 10) separated by white space and save the file as grade.txt. Write a Java program to read the numbers from grade.txt, calculate the average grade and print the output.
In a notepad, type five names (one name per line) and save the file as name.txt. Create a GUI from which you can select (browse button) the file name.txt and write (create button) the names in name.txt to file name_out.txt (one name per line).