Docsity

Java I/O and Threads: Lecture 7, Study Guides, Projects, Research of Java Programming

Partial preview of the text

Download Java I/O and Threads: Lecture 7 and more Study Guides, Projects, Research Java Programming in PDF only on Docsity!

CS 190 - Java

Introduction to Java

Andy Mroczkowski

[email protected]

Department of Computer Science

Drexel University

March 3, 2008 / Lecture 7

Outline

Course Status

Course Information & Schedule

Assignments & Final Project

Files & I/O

Working with Files

Streams

Interactive I/O

Scanning & Formatting

Threads

Basics

Threads in Java

Synchronization

synchronized

Summary

Project

Intro

Schedule

Jan 7 Course Overview, Introduction to Java

Jan 14 No Class

Jan 21 No Class (University Holiday)

Jan 28 Object Oriented Concepts, Control Statements

Feb 4 Access Control, Intialization & Cleanup, Reuse, Interfaces,

Feb 11 Containers, Exceptions, Polymorphism, Midterm Review

Feb 18 Midterm, Inner-Classes

Feb 25 Type Information, Generics, Arrays

Mar 3 Files & I/O, Threading

Mar 10 GUI, Special Topics (Networking, Reflection)

Mar 17 Final Project?

Also subject to change

Assignment 5

• Questions?

Working with Files

The File class

• Java object to represent an actual file

• In the UNIX tradition, dirs are files too

• Useful for working with paths too

The File class

• Java object to represent an actual file

• In the UNIX tradition, dirs are files too

• Useful for working with paths too

File example

import j a v a. i o. F i l e ;

public class JavaLS {

public s t a t i c void main ( S t r i n g [ ] args ) { F i l e pwd = new F i l e ( ". " ) ; S t r i n g [ ] l i s t = pwd. l i s t ( ) ; f o r ( i n t i = 0 ; i < l i s t. l e n g t h ; i ++ ) { System. o u t. p r i n t l n ( l i s t [ i ] ) ; } } }

Streams

Streams

• Input Streams

• Output Streams

Types of OutputStream

• ByteArrayOutputStream

• FileOutputStream

• PipedOutputStream

• FilterOutputStream

Using Streams

Examples from The Java Tutorials

http://java.sun.com/docs/books/tutorial/essential/io/index.html

Byte Streams

• Used for reading raw bytes

• Image files, audio files, almost anything but text

• FileInputStream

• FileOutputStream

Copying a Text File

import j a v a. i o. F i l e I n p u t S t r e a m ; import j a v a. i o. F i l e O u t p u t S t r e a m ; import j a v a. i o. IOException ;

public class CopyBytes { public s t a t i c void main ( S t r i n g [ ] args ) throws IOException { F i l e I n p u t S t r e a m i n = n u l l ; F i l e O u t p u t S t r e a m ou t = n u l l ; t r y { i n = new F i l e I n p u t S t r e a m ( " i n f i l e. t x t " ) ; o ut = new F i l e O u t p u t S t r e a m ( " o u t f i l e. t x t " ) ; i n t c ;

while ( ( c = i n. read ( ) )! = −1) { o ut. w r i t e ( c ) ; }

} f i n a l l y { i f ( i n! = n u l l ) { i n. c l o s e ( ) ; } i f ( o ut! = n u l l ) { o ut. c l o s e ( ) ; } } } }