Обработка исключительных ситуаций, работа с файлами  Исключительные ситуации  Классы File, InputStream, RandomAccessFile, FileReader, BufferedReader,

Slides:



Advertisements
Similar presentations
1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
Advertisements

Jan Java I/O Yangjun Chen Dept. Business Computing University of Winnipeg.
Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
Lecture 15: I/O and Parsing
MOD III. Input / Output Streams Byte streams Programs use byte streams to perform input and output of 8-bit bytes. This Stream handles the 8-bit.
©SoftMoore ConsultingSlide 1 Appendix G: Java Input/Output.
© Marty Hall, Larry Brown Web core programming 1 Java Input/Output Training Courses: Java, JSP, Servlets, Struts,
Unit 201 FILE IO Types of files Opening a text file for reading Reading from a text file Opening a text file for writing/appending Writing/appending to.
Sakir YUCEL MISM/MSIT Carnegie Mellon University Lecture: I/O
File I/O in Java CS 311, Winter File Basics Recall that a file is block structured. What does this mean? What happens when an application opens.
1 Text File I/O Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l.
1 Streams Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l Writing.
Strings and File I/O. Strings Java String objects are immutable Common methods include: –boolean equalsIgnoreCase(String str) –String toLowerCase() –String.
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
Performance measurements for inter-process communication.
פיתוח מונחה עצמים – שפת JAVA קבצים. References קורס "שיטות בהנדסת תוכנה", הפקולטה למדעי המחשב, הטכניון. קורס "מערכות מידע מבוזרות", הפקולטה להנדסת תעשייה.
Java Programming: I/O1 Java I/O Reference: java.sun.com/docs/books/tutorial/essential/io/
Lecture 7 Exceptions and I/O. Overview of the exception hierarchy A simplified diagram of the exception hierarchy in Java Throwable ErrorException IOException.
Georgia Institute of Technology Speed part 3 Barb Ericson Georgia Institute of Technology May 2006.
Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File class.
5-Oct-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Streams and Files Maj Joel Young.
1 Chapter 11 – Files and Streams 1 Introduction What are files? –Long-term storage of large amounts of data –Persistent data exists after termination of.
Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams F Text Input and Output on the Console.
Program data (instance variables, local variables, and parameters) is transient, because its lifetime ends with the program...if not, before. Sometimes.
Based on OOP with Java, by David J. Barnes Input-Output1 The java.io Package 4 Text files Reader and Writer classes 4 Byte stream files InputStream, FileInputStream,
I / O in java. java.io BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter ByteArrayInputStream ByteArrayOutputStream CharArrayReader.
Programs & Data Files Notes Data information processed by word processing, spreadsheet or other application programs are stored as data files. Java programs,
Networks Sockets and Streams. TCP/IP in action server ports …65535 lower port numbers ( ) are reserved port echo7 time13 ftp20 telnet23.
The Java I/O Classes and Interfaces cont’d
File IO Basics By Dan Fleck Coming up: Data Streams.
By Rachel Thompson and Michael Deck.  Java.io- a package for input and output  File I/O  Reads data into and out of the console  Writes and reads.
Input/output Input in java is stream based.A stream represents sequence of bytes or characters. Stream provides an abstract view of I/O. Stream can be.
L5: Input & Output COMP206, Geoff Holmes and Bernhard Pfahringer.
Java Input/Output. Reading standard input Surprisingly complicated (GUI focus) Old-fashioned way: BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
CS101 Lab “File input/Output”. File input, output File : binary file, text file READ/WRITE class of “text file” - File Reading class : FileReader, BufferedReader.
1 Software 1 Java I/O. 2 The java.io package The java.io package provides: Classes for reading input Classes for writing output Classes for manipulating.
Lecture 5 I/O and Parsing
CIS Intro to JAVA Lecture Notes Set 6 2-June-05.
CSI 3125, Preliminaries, page 1 Java I/O. CSI 3125, Preliminaries, page 2 Java I/O Java I/O (Input and Output) is used to process the input and produce.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
Programs & Data Files Notes Data information processed by word processing, spreadsheet or other application programs are stored as data files. Java.
Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that.
Strings and File I/O. Strings Java String objects are immutable Common methods include: –boolean equalsIgnoreCase(String str) –String toLowerCase() –String.
CS202 Java Object Oriented Programming Input and Output Chengyu Sun California State University, Los Angeles.
Java IO Exploring the java.io package and living to talk about it.
Fundamental of Java Programming
IO in java.
Sequential files creation & writing
IO in java.
OO Design and Programming II I/O: Reading and Writing
Lesson 8: More File I/O February 5, 2008
Strings and File I/O.
12: The Java I/O System stream model.
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
Објектно орјентисано програмирање
Методика наставе рачунарства
File class File myFile=new File(“c:/javaDemo/aa
JAVA IO.
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
Reading and Writing Text Files
18 File i/o, Parsing.
Text File Read and Write Method
Files and Streams in Java
CS 240 – Advanced Programming Concepts
ECE 122 April 14, 2005.
EEC 484/584 Computer Networks
Java IO Packages Prepared by Mrs.S.Amudha AP/SWE
David Davenport Spring 2005
Presentation transcript:

Обработка исключительных ситуаций, работа с файлами  Исключительные ситуации  Классы File, InputStream, RandomAccessFile, FileReader, BufferedReader, BufferedWriter, FileWriter, InputStreamReader, InputStreamWriter

try, catch  throw new Exception();  try { … } catch( Exception e) { … }  public void f() throws Exception { … }

Создание своих исключений class SimpleException extends Exception { }

Работа с файловой системой. Класс File  Это скорее путь к файлу  Соответствует файлу или папке: new File("test.txt") new File(".")  Методы File.separator - \ или / String[] list() - список файлов папки boolean isDirectory() String getPath() String getAbsolutePath() File getAbsoluteFile() String getCanonicalPath() File getCanonicalFile() boolean exists() boolean createNewFile() boolean delete() boolean renameTo(File f) long length()

Работа с двоичными файлами  Чтение из файла. Класс InputStream File file = new File("file.tst"); InputStream str = new FileInputStream(file); long length = file.length(); byte[] bytes = new byte[(int)length]; int readed = str.read(bytes,0,length); str.close();  Запись в файл. Класс RandomAccessFile try { File f = new File("file.tst"); RandomAccessFile raf = new RandomAccessFile(f,"rw"); raf.seek(f.length()); raf.writeChars("The End"); raf.close(); } catch IOException e) { System.out.println("Ошибка при чтении или записи файла"); }

Работа с файлами  Чтение из текстового файла try { BufferedReader in = new BufferedReader(new FileReader("file.txt")); String str; while( (str=in.readLine()) != null) { // } in.close(); } catch(IOException e) { System.out.println("Ошибка при чтении"); }  Запись (дополнение) в текстовый файл try { BufferedWriter out = new BufferedWriter(new FileWriter("file.txt",true)); out.write("It’s a new line"); in.close(); } catch(IOException e) { System.out.println("Ошибка при записи"); }

Указание кодировки  Чтение из текстового файла try { BufferedReader in = new BufferedReader( new InputStreamReader(new FileInputStream("file.txt"),"windows-1251")); String str; while( (str=in.readLine()) != null) { // } in.close(); } catch(IOException e) { System.out.println("Ошибка при чтении"); }  Запись в текстовый файл try { BufferedWriter out = new BufferedWriter( new OutputStreamWriter(new FileOutputStream("file.txt"),"windows-1251")); out.write("Мы дописали этот текст"); out.close(); } catch(IOException e) { System.out.println("Ошибка при записи"); }