Java NIO. Rein Raudjärv Nov 19th 2012 Java Fundamentals

Size: px
Start display at page:

Download "Java NIO. Rein Raudjärv Nov 19th 2012 Java Fundamentals"

Transcription

1 Java NIO Rein Raudjärv Nov 19th 2012 Java Fundamentals

2 Agenda 1. NIO 1. Basics 2. Channels 3. Selectors 2. NIO.2 (File I/O) 1. Basics 2. Metadata

3 NIO BASICS

4 Based On Jakob Jenkov hjp://tutorials.jenkov.com/java- nio/index.html

5 What is NIO? Java NIO (New IO) is an alternaqve IO API for Java Since Java 1.4 (2002) It enables you to do asynchronous IO.

6 Reading Example FileChannel fc = new RandomAccessFile("in.txt", "r").getchannel(); try { ByteBuffer buf = ByteBuffer.allocate(48); while (fc.read(buf)!= - 1) { buf.flip(); while (buf.hasremaining()) System.out.print((char) buf.get()); buf.clear(); } } finally { fc.close(); }

7 WriQng Example FileChannel fc = new RandomAccessFile("out.txt", "rw").getchannel(); try { String data = "Hello"; ByteBuffer buf = ByteBuffer.allocate(48); buf.clear(); buf.put(data.getbytes()); buf.flip(); fc.write(buf); } finally { fc.close(); }

8 WriQng Example (2) FileChannel fc = new RandomAccessFile( "out.txt", "rw ).getchannel(); try { } String data = "Hello"; ByteBuffer buf = ByteBuffer.wrap(data.getBytes()); fc.write(buf); finally { fc.close(); }

9 Channels FileChannel DatagramChannel SocketChannel ServerSocketChannel

10 Buffers ByteBuffer CharBuffer DoubleBuffer FloatBuffer IntBuffer LongBuffer ShortBuffer

11 Buffer State Mode (WriQng or Reading) Capacity PosiQon Limit 0 <= posiqon <= limit <= capacity

12 Buffer State

13 Buffer Usage 1. Write data into the Buffer 2. Call buffer.flip() 3. Read data out of the Buffer 4. Call buffer.clear() or buffer.compact()

14 WriQng Data to a Buffer Copy data from a Channel into a Buffer int bytesread = inchannel.read(buf); Write data into the Buffer yourself, via the buffer's put() methods. buf.put(127);

15 Reading Data from a Buffer Copy data from a buffer into a Channel. int byteswrijen = outchannel.write(buf); Read data from the Buffer yourself, using one of the get() methods. byte abyte = buf.get();

16 ScaJering Reads ByteBuffer header = ByteBuffer.allocate(128); ByteBuffer body = ByteBuffer.allocate(1024); ByteBuffer[] bufferarray = { header, body }; channel.read(buffers);

17 Gathering Writes ByteBuffer header = ByteBuffer.allocate(128); ByteBuffer body = ByteBuffer.allocate(1024); //write data into buffers ByteBuffer[] bufferarray = { header, body }; channel.write(buffers);

18 NIO CHANNELS

19 Channels FileChannel DatagramChannel SocketChannel ServerSocketChannel

20 File Channel Has current posiaon in its file Has current size of its file Can read/write bytes at absolute posiaons A region can be mapped directly into memory Updates can be forced out to the disk Can transfer bytes directly to/from a channel A region can be locked against other accesses

21 Obtaining File Channel Instance FileInputStream.getChannel() FileOutputStream.getChannel() RandomAccessFile.getChannel()

22 Closing File Channel FileChannel.close() Also closes the object whose getchannel() method returned the Channel FileInputStream/FileOutputStream/ RandomAccessFile.close() Also closes the Channel

23 Transfer From RandomAccessFile fromfile = null; RandomAccessFile tofile = null; try { fromfile = new RandomAccessFile("fromFile.txt", "rw"); tofile = new RandomAccessFile("toFile.txt", "rw"); FileChannel fromchannel = fromfile.getchannel(); FileChannel tochannel = tofile.getchannel(); tochannel.transferfrom(fromchannel, 0, fromchannel.size()); } finally { IOUQls.closeQuietly(fromFile); IOUQls.closeQuietly(toFile); }

24 Transfer To RandomAccessFile fromfile = null; RandomAccessFile tofile = null; try { fromfile = new RandomAccessFile("fromFile.txt", "rw"); tofile = new RandomAccessFile("toFile.txt", "rw"); FileChannel fromchannel = fromfile.getchannel(); FileChannel tochannel = tofile.getchannel(); fromchannel.transferto(0, fromchannel.size(), tochannel); } finally { IOUQls.closeQuietly(fromFile); IOUQls.closeQuietly(toFile); }

25 Socket Channel SocketChannel sc = SocketChannel.open(); try { sc.connect(new InetSocketAddress("localhost", 80));... } finally { sc.close(); }

26 Transfer Socket To File FileChannel fc = new RandomAccessFile("out", "rw").getchannel(); try { int pos = 0; long bytesread; while ((bytesread = fc.transferfrom(sc, pos, 4096)) > 0) pos += bytesread; } finally { fc.close(); }

27 Server Socket Channel ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket().bind(new InetSocketAddress(80)); while (true) { } SocketChannel sc = ssc.accept(); handle(sc);

28 WriQng To Datagram Channel DatagramChannel channel = DatagramChannel.open(); String data = "Hello"; ByteBuffer buf = ByteBuffer.wrap(data.getBytes()); int bytessent = channel.send( buf, new InetSocketAddress("localhost", 9999)); channel.connect( new InetSocketAddress("localhost", 9999)); int bytessent = channel.write(buf);

29 Reading From Datagram Channel DatagramChannel channel = DatagramChannel.open(); ByteBuffer buf = ByteBuffer.allocate(1024); buf.clear(); channel.socket().bind(new InetSocketAddress(9999)); SocketAddress sa = channel.receive(buf); channel.connect( new InetSocketAddress("localhost", 8888)); int bytesreceived = channel.read(buf);

30 NIO SELECTORS

31 Selectors A Selector allows a single thread to handle mulqple Channel's.

32 Channel Events Connect Accept Read Write

33 Registering Channel Channel Selector Interest Set (events) Ready Set (events) An ajached object (opqonal)

34 Registering Datagram Channels Selector selector = Selector.open(); for (int port : ports) { DatagramChannel dc = DatagramChannel.open(); dc.configureblocking(false); dc.bind(new InetSocketAddress(port)); dc.register(selector, SelecAonKey.OP_READ); }

35 SelecQng Datagram Channels while (true) { } selector.select(); for (Iterator<SelecQonKey> it = } selector.selectedkeys().iterator(); it.hasnext();) { SelecQonKey sk = it.next(); DatagramChannel dc = (DatagramChannel) sk.channel(); // read channel it.remove();

36 Registering Server Socket Channel Selector selector = Selector.open(); ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.configureblocking(false); ssc.bind(new InetSocketAddress(4000)); ssc.register(selector, SelecAonKey.OP_ACCEPT);

37 SelecQng (Server) Socket Channels while (true) { selector.select(); for (Iterator<SelecQonKey> it = selector.selectedkeys().iterator(); it.hasnext();) { SelecQonKey key = it.next(); if (key.isreadable()) read(key); else if (key.isacceptable()) accept(key); it.remove(); } }

38 Reading Socket Channel void read(selecqonkey key) { SocketChannel sc = (SocketChannel) key.channel(); ByteBuffer buf = ByteBuffer.allocate(1024); int bytesread = sc.read(buf); if (bytesread == - 1) sc.close(); else handle(buf); }

39 AccepQng Socket Channel void accept(selecqonkey key) { ServerSocketChannel ssc = (ServerSocketChannel) key.channel(); } SocketChannel sc = ssc.accept(); sc.configureblocking(false); Selector selector = key.selector(); sc.register(selector, SelecAonKey.OP_READ);

40 NIO.2 (FILE I/O)

41 Based On File I/O (Featuring NIO.2) Java Tutorial hjp://docs.oracle.com/javase/tutorial/ essenqal/io/fileio.html

42 What is NIO.2? File Paths File OperaQons Managing Metadata Walking the File Tree Finding Files Watching a Directory for Changes

43 Other Benefits Supports symbolic links Improved support for relaqve paths Improved support for directory lisqngs Improved error handling

44 Paths Paths.get("c:\\example\\data\\input.txt"); Paths.get("/example/data/input.txt"); Paths.get("example/data/input.txt"); Paths.get("example\\data\\input.txt"); Paths.get("example", "data", "input.txt"); Paths.get("/", "example", "data", "input.txt"); Paths.get( URI.create("file:/example/data/input.txt"));

45 Path class Path { String tostring() Path getfilename() Path getname(int index) int getnamecount() Path subpath(int beginindex, int endindex) Path getparent() Path getroot() }

46 Path (2) class Path { Path normalize() boolean isabsolute() Path toabsolutepath() Path resolve(path other) Path relaqvize(path other) File tofile() URI touri() }

47 Path (3) Path torealpath(linkopqon... opqons) throws IOExcepQon enum LinkOpQon { NOFOLLOW_LINKS; } apath.torealpath() follows symbolic links apath.torealpath(linkopqon.nofollow_links) doesn t follow symbolic links

48 Checking Files Files { boolean exists(path path, LinkOpQon... opqons) boolean notexists(path path, LinkOpQon... opqons) boolean isreadable(path path) boolean iswritable(path path) boolean isexecutable(path path) boolean issamefile(path path, Path path2) throws IOExcepQon }

49 DeleQng Files Files { void delete(path path) throws IOExcepQon boolean deleteifexists(path path) throws IOExcepQon } May throw NoSuchFileExcepQon DirectoryNotEmptyExcepQon

50 Coping Files Files { } Path copy(path source, Path target, CopyOpQon... opqons) long copy(inputstream in, OutputStream out) long copy(inputstream in, Path target, CopyOpQon... opqons) long copy(path source, OutputStream out)

51 Coping Files (2) enum StandardCopyOpQon implements CopyOpQon { REPLACE_EXISTING, } COPY_ATTRIBUTES, ATOMIC_MOVE; enum LinkOpQon implements CopyOpQon { } NOFOLLOW_LINKS;

52 Moving Files Files { } Path move(path source, Path target, CopyOpQon... OpQons) Supported opqons: REPLACE_EXISTING ATOMIC_MOVE

53 LisQng Directories try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) { for (Path file: stream) System.out.println(file.getFileName()); } catch (IOExcepQon DirectoryIteratorExcepQon x) { } System.err.println(x);

54 Filtering Directory LisQngs DirectoryStream<Path> stream = Files.newDirectoryStream(dir, new Filter<Path>() { boolean accept(path path) { } }); return Files.isDirectory(path); DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.class");

55 Reading and WriQng Files class Files { byte[] readallbytes(path path) } List<String> readalllines(path path, Charset cs) Path write(path p, byte[] bytes, OpenOpQon... oo) Path write(path path, Iterable<? Extends CharSequence> lines, Charset c, OpenOpQon... oo)...

56 NIO.2 FILE METADATA

57 Basic File AJributes Files { long size(path path) boolean isdirectory(path path, LinkOpQon... lo) boolean isregularfile(path path, LinkOpQon... lo) boolean issymboliclink(path path) boolean ishidden(path path) }

58 Last Modified Time FileTime Qme = Files.getLastModifiedTime(path); long millis = Qme.toMillis(); long millis = System.currentTimeMillis(); FileTime Qme = FileTime.fromMillis(millis); Files.setLastModifiedTime(path, Qme);

59 File Owner UserPrincipal owner = Files.getOwner(path); String name = owner.getname(); String name = "James"; UserPrincipal owner = path.getfilesystem(). getuserprincipallookupservice(). lookupprincipalbyname(name); Files.setOwner(path, owner);

60 Geng POSIX File Permissions Set<PosixFilePermission> perms = Files.getPosixFilePermissions(path); boolean ownerread = perms.contains( PosixFilePermission.OWNER_READ); System.out.println(perms); System.out.println( PosixFilePermissions.toString(perms));

61 Seng POSIX File Permissions Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); perms.add(posixfilepermission.owner_read); Files.setPosixFilePermissions(path, perms); Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxr- xr- x"); Files.setPosixFilePermissions(path, perms);

62 POSIX File Permissions OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_WRITE GROUP_EXECUTE OTHERS_READ OTHERS_WRITE OTHERS_EXECUTE

63 Single File AJributes Files { } Object geta^ribute(path path, String ajribute, LinkOpQon... opqons) Path seta^ribute(path path, String ajribute, Object value, LinkOpQon... opqons)

64 Reading File AJributes Files { } <A extends BasicFileAJributes> A reada^ributes( Path path, Class<A> type, LinkOpQon... opqons)

65 File AJribute Views Files { } <V extends FileAJributeView> V getfilea^ributeview( Path path, Class<V> type, LinkOpQon... opqons)

66 Supported AJributes FileAJributeView BasicFileAJributeView DosFileAJributeView PosixFileAJributeView FileOwnerAJributeView AclFileAJributeView UserDefinedFileAJributeView BasicFileAJributes DosFileAJributes PosixFileAJributes

67 DOS File AJributes DosFileAJributes ajr = Files.readAJributes( path, DosFileAJributes.class); interface DosFileAJributes extends BasicFileAJributes { boolean isreadonly() boolean ishidden() boolean isarchive() boolean issystem() }

68 Summary Mostly basic IO is good enough and it may be even faster than NIO Use NIO for direct file transfers, memory mappings, file locking etc Use NIO Selectors for mulqple sockets with low bandwidth

69 Summary (2) Use NIO.2 File API for faster directory lisqngs bejer metadata listening for changes finding files

70 QUESTIONS?

71 Homework 11 Write a Java program which mirrors a directory (not recursively) 1. Take the source and target directory paths as input arguments. 1. Fail if source directory does not exist. 2. Create the target directory if it doesn't exist.

72 Homework 11 (2) 2. On startup compare directory lisqngs (use java.nio.file.directorystream) and Copy new files from source to target directory. 2. Copy updated (check last modified Qmes) files from source to target directory. 3. Remove files from target directory which have been removed from source directory. 4. Ignore sub directories in both source and target directory.

73 Homework 11 (3) 3. Watch source directory for changes (use java.nio.file.watchservice) and mirror them into the target directory. 1. Exit when the source directory gets removed (watch key is invalid). 4. Use Java 7 File APIs (java.nio.file) instead of the old (java.io.file). 5. Print a message about each file operaqon you make. 6. Source directory must not be altered.

Process I/O and File NIO.2

Process I/O and File NIO.2 Process I/O and File NIO.2 Java Fundamentals 2014, Tartu Neeme Praks @nemecec Agenda 1. Process I/O 1. StarAng Processes 2. Handling I/O 3. Stopping Processes 2. New File API (NIO.2) 1. Basics 2. Metadata

More information

Introduction to NIO: New I/O

Introduction to NIO: New I/O Chapter 2 Introduction to NIO: New I/O Advanced Topics in Java Khalid Azim Mughal khalid@ii.uib.no http://www.ii.uib.no/~khalid/atij/ Version date: 2004-09-01 ATIJ 2: Introduction to NIO: New I/O 2-1/36

More information

Outline of Topics. UDP Socket Java Programming. Multicast in Java. Real-time protocol (RTP) XMPP and Jingle protocols. Java I/O and New IO (NIO)

Outline of Topics. UDP Socket Java Programming. Multicast in Java. Real-time protocol (RTP) XMPP and Jingle protocols. Java I/O and New IO (NIO) Outline Outline of Topics UDP Socket Java Programming Multicast in Java Real-time protocol (RTP) XMPP and Jingle protocols Java I/O and New IO (NIO) UDP Socket Java Programming User Datagram Protocol (UDP)

More information

NIO AND NIO2. Introduction. Module 10

NIO AND NIO2. Introduction. Module 10 Module 10 NIO AND NIO2 Introduction > Java SE 1.4 introduced a number of features for improved input/output processing, collectively called the "new I/O," in the java.nio package. > Of course, the "new"

More information

I/O Java Fundamentals Rein Raudjärv 2016, Tartu

I/O Java Fundamentals Rein Raudjärv 2016, Tartu I/O Java Fundamentals Rein Raudjärv 2016, Tartu 1 Agenda I/O Streams File I/O 2 Some Examples Github repository http://bit.ly/jf-github Checkout the project (or fork) Import the io sub project to your

More information

Ch.11 Nonblocking I/O

Ch.11 Nonblocking I/O CSB541 Network Programming 網路程式設計 Ch.11 Nonblocking I/O 吳俊興國立高雄大學資訊工程學系 Outline 11.1 An Example Client 11.2 An Example Server 11.3 Buffers 11.4 Channels 11.5 Readiness Selection 2 Java I/O Two typical

More information

Reading and Writing Files

Reading and Writing Files Reading and Writing Files 1 Reading and Writing Files Java provides a number of classes and methods that allow you to read and write files. Two of the most often-used stream classes are FileInputStream

More information

SPL - PS12. Reactor and Java New-IO (nio) classes

SPL - PS12. Reactor and Java New-IO (nio) classes SPL - PS12 Reactor and Java New-IO (nio) classes Multi-Threaded server, as seen in Tirgul 11 - one thread is in charge of accepting new connections - opens a new thread for each new client. - Thus, handling

More information

Improving Java Network Programming. Brian Runk, 25 Apr 2006

Improving Java Network Programming. Brian Runk, 25 Apr 2006 Improving Java Network Programming Brian Runk, b.runk@morganstanley.com 25 Apr 2006 Topics Background A simple distributed application java.net programming model java.nio programming model A better programming

More information

Effec%ve So*ware. Lecture 6: Non-blocking I/O, C10K, efficient networking. David Šišlák

Effec%ve So*ware. Lecture 6: Non-blocking I/O, C10K, efficient networking. David Šišlák Effec%ve So*ware Lecture 6: Non-blocking I/O, C10K, efficient networking David Šišlák david.sislak@fel.cvut.cz Network Communica%on OSI Model 10 th April 2017 ESW Lecture 6 2 Network Communica%on HTTP

More information

Project 0. Danyang Zhuo CSE sp Sec;on #2

Project 0. Danyang Zhuo CSE sp Sec;on #2 Project 0 Danyang Zhuo CSE 461 15sp Sec;on #2 Proj0 You have to implement: Mul;- UDP Server Mul;- UDP Client Async IO UDP Server Async IO UDP Client Your server must support mul;ple clients Submit Format

More information

Outline. Network Applications: High-Performance Network Servers. Recap: Server Processing Steps. Worker. Recap: Main Thread. Recap: Progress So Far

Outline. Network Applications: High-Performance Network Servers. Recap: Server Processing Steps. Worker. Recap: Main Thread. Recap: Progress So Far Outline Network Applications: High-Performance Network Servers Y. Richard Yang http://zoo.cs.yale.edu/classes/cs433/ Ø Admin and recap High performance servers Thread Per-request thread Thread pool Busy

More information

JDK 7 (2011.7) JDK 7. knight76.tistory.com Knight76 at gmail.com

JDK 7 (2011.7) JDK 7. knight76.tistory.com Knight76 at gmail.com JDK 7 (2011.7) JDK 7 #3 NIO2 knight76.tistory.com Knight76 at gmail.com 1 NIO2 2 3 Java SE 7 http://download.oracle.com/javase/7/docs/tec hnotes/guides/io/enhancements.html#7 http://java.sun.com/developer/technicalarticle

More information

Advanced Programming Methods. Lecture 3 - Java IO Operations

Advanced Programming Methods. Lecture 3 - Java IO Operations Advanced Programming Methods Lecture 3 - Java IO Operations Overview 1. Java IO 2. Java NIO 3. Try-with-resources Java IO Package java.io Java.IO classes working on bytes (InputStream, OutputStream) Classes

More information

Network Applications: High-Performance Network Servers

Network Applications: High-Performance Network Servers Network Applications: High-Performance Network Servers Y. Richard Yang http://zoo.cs.yale.edu/classes/cs433/ 10/01/2013 Outline Ø Admin and recap High performance servers Thread Per-request thread Thread

More information

The Sun Certified Java Developer Exam with J2SE 1.4 MEHRAN HABIBI, JEREMY PATTERSON, AND TERRY CAMERLENGO

The Sun Certified Java Developer Exam with J2SE 1.4 MEHRAN HABIBI, JEREMY PATTERSON, AND TERRY CAMERLENGO The Sun Certified Java Developer Exam with J2SE 1.4 MEHRAN HABIBI, JEREMY PATTERSON, AND TERRY CAMERLENGO The Sun Certified Java Developer Exam with J2SE 1.4 Copyright 2002 by Mehran Habibi, Jeremy Patterson,

More information

Hacking the File System with JDK Release 7

Hacking the File System with JDK Release 7 Hacking the File System with JDK Release 7 Alan Bateman Sun Microsystems Inc. Carl Quinn Netflix Inc. Agenda Introduction Path operations File operations Directories Agenda Introduction Path operations

More information

Introduction to Network Programming using Java

Introduction to Network Programming using Java Introduction to Network Programming using Java 1 Development platform Starting Point Unix/Linux/Windows available in the department or computing centre More information http://www.tkk.fi/cc/computers/

More information

CS 251 Intermediate Programming Java I/O File I/O

CS 251 Intermediate Programming Java I/O File I/O CS 251 Intermediate Programming Java I/O File I/O Brooke Chenoweth University of New Mexico Spring 2018 Paths Most file systems store files in a hierarchical structure. The top of the directory tree is

More information

CharBuffer view of those bytes: This creates a view of the original ByteBuffer, which behaves like a. buffer as an int, you could do the following:

CharBuffer view of those bytes: This creates a view of the original ByteBuffer, which behaves like a. buffer as an int, you could do the following: Object Oriented Programming 1. More Java new I/O 2. Introduction to Threads We discussed only this Simplified Channel Hierarchy ByteChannel Channel SelectableChannel FileChannel

More information

Networking in Java. Java Fundamentals. Dmitri Gabbasov Tartu 2016

Networking in Java. Java Fundamentals. Dmitri Gabbasov Tartu 2016 Networking in Java Java Fundamentals Dmitri Gabbasov Tartu 2016 The java.net package java.net.socket represents a TCP connection to a remote endpoint java.net.serversocket represents a TCP endpoint that

More information

A RESTful Java Framework for Asynchronous High-Speed Ingest

A RESTful Java Framework for Asynchronous High-Speed Ingest A RESTful Java Framework for Asynchronous High-Speed Ingest Pablo Silberkasten Jean De Lavarene Kuassi Mensah JDBC Product Development October 5, 2017 3 Safe Harbor Statement The following is intended

More information

COMP1008 An overview of Polymorphism, Types, Interfaces and Generics

COMP1008 An overview of Polymorphism, Types, Interfaces and Generics COMP1008 An overview of Polymorphism, Types, Interfaces and Generics Being Object-Oriented Exploiting the combination of: objects classes encapsulation inheritance dynamic binding polymorphism pluggability

More information

Timber: Time as a Basis for Embedded real-time systems. Andrew Black, Magnus Carlsson, Mark Jones, Dick Kieburtz, Johan Nordlander

Timber: Time as a Basis for Embedded real-time systems. Andrew Black, Magnus Carlsson, Mark Jones, Dick Kieburtz, Johan Nordlander Timber: Time as a Basis for Embedded real-time systems Andrew Black, Magnus Carlsson, Mark Jones, Dick Kieburtz, Johan Nordlander Timber objectives:! Design a language with explicit time behavior! Explore

More information

JAVA.IO.FILE CLASS. static String pathseparator -- This is the system-dependent path-separator character, represented as a string for convenience.

JAVA.IO.FILE CLASS. static String pathseparator -- This is the system-dependent path-separator character, represented as a string for convenience. http://www.tutorialspoint.com/java/io/java_io_file.htm JAVA.IO.FILE CLASS Copyright tutorialspoint.com Introduction The Java.io.File class is an abstract representation of file and directory pathnames.

More information

Outline. More on MINA features. ú Performance. ú Separating low- level IO handling from the protocol from the business logic.

Outline. More on MINA features. ú Performance. ú Separating low- level IO handling from the protocol from the business logic. Ehab Ababneh Outline The Problem: Thousands of Clients. Solution: Non- Blocking IO. The Reactor Pattern: Down to the roots of NBIO. NBIO is hard, just like multithreading. Frameworks are a bliss!... Apache

More information

Programmieren II. Collections. Alexander Fraser. May 28, (Based on material from T. Bögel)

Programmieren II. Collections. Alexander Fraser. May 28, (Based on material from T. Bögel) Programmieren II Collections Alexander Fraser fraser@cl.uni-heidelberg.de (Based on material from T. Bögel) May 28, 2014 1 / 46 Outline 1 Recap Paths and Files Exceptions 2 Collections Collection Interfaces

More information

File System Interface. ICS332 Operating Systems

File System Interface. ICS332 Operating Systems File System Interface ICS332 Operating Systems Files and Directories Features A file system implements the file abstraction for secondary storage It also implements the directory abstraction to organize

More information

Random Access Filing

Random Access Filing Random Access Filing Two types of storage Digital devices have two broad types of storage - volatile and non-volatile. Volatile storage means the data is lost when power is removed. When the device is

More information

Distributed Systems Recitation 2. Tamim Jabban

Distributed Systems Recitation 2. Tamim Jabban 15-440 Distributed Systems Recitation 2 Tamim Jabban Agenda Communication via Sockets in Java (this enables you to complete PS1 and start P1 (goes out today!)) Multi-threading in Java Coding a full Client-Server

More information

Useful stuff in Java 7. New stuff that s actually useful

Useful stuff in Java 7. New stuff that s actually useful Useful stuff in Java 7 New stuff that s actually useful Try with resources Recognize this? try { stmt = con.createstatement(); ResultSet rs = stmt.executequery(query); System.out.println("Coffees bought

More information

C17: File I/O and Exception Handling

C17: File I/O and Exception Handling CISC 3120 C17: File I/O and Exception Handling Hui Chen Department of Computer & Information Science CUNY Brooklyn College 10/24/2017 CUNY Brooklyn College 1 Outline Recap and issues Exception Handling

More information

File IO. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 20

File IO. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 20 File IO Computer Science and Engineering College of Engineering The Ohio State University Lecture 20 I/O Package Overview Package java.io Core concept: streams Ordered sequences of data that have a source

More information

CS 251 Intermediate Programming Java I/O Streams

CS 251 Intermediate Programming Java I/O Streams CS 251 Intermediate Programming Java I/O Streams Brooke Chenoweth University of New Mexico Spring 2018 Basic Input/Output I/O Streams mostly in java.io package File I/O mostly in java.nio.file package

More information

JAVA - FILE CLASS. The File object represents the actual file/directory on the disk. Below given is the list of constructors to create a File object

JAVA - FILE CLASS. The File object represents the actual file/directory on the disk. Below given is the list of constructors to create a File object http://www.tutorialspoint.com/java/java_file_class.htm JAVA - FILE CLASS Copyright tutorialspoint.com Java File class represents the files and directory pathnames in an abstract manner. This class is used

More information

Distributed Systems Recitation 2. Tamim Jabban

Distributed Systems Recitation 2. Tamim Jabban 15-440 Distributed Systems Recitation 2 Tamim Jabban Project 1 Involves creating a Distributed File System (DFS) Released yesterday When/If done with PS1, start reading the handout Today: Socket communication!

More information

RCU. ò Walk through two system calls in some detail. ò Open and read. ò Too much code to cover all FS system calls. ò 3 Cases for a dentry:

RCU. ò Walk through two system calls in some detail. ò Open and read. ò Too much code to cover all FS system calls. ò 3 Cases for a dentry: Logical Diagram VFS, Continued Don Porter CSE 506 Binary Formats RCU Memory Management File System Memory Allocators System Calls Device Drivers Networking Threads User Today s Lecture Kernel Sync CPU

More information

VFS, Continued. Don Porter CSE 506

VFS, Continued. Don Porter CSE 506 VFS, Continued Don Porter CSE 506 Logical Diagram Binary Formats Memory Allocators System Calls Threads User Today s Lecture Kernel RCU File System Networking Sync Memory Management Device Drivers CPU

More information

JAVA V Input/Output Java, winter semester

JAVA V Input/Output Java, winter semester JAVA Input/Output 1 Overview package java.io basic input/output streams bytes since JDK1.1 Reader and Writer chars (Unicode) package java.nio since JDK1.4 channels, buffers increased performance classes

More information

JAVA Input/Output Java, winter semester

JAVA Input/Output Java, winter semester JAVA Input/Output 1 Overview package java.io basic input/output streams bytes since JDK1.1 Reader and Writer chars (Unicode) package java.nio since JDK1.4 channels, buffers increased performance classes

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

Cluster Consensus When Aeron Met Raft. Martin Thompson

Cluster Consensus When Aeron Met Raft. Martin Thompson Cluster When Aeron Met Raft Martin Thompson - @mjpt777 What does mean? con sen sus noun \ kən-ˈsen(t)-səs \ : general agreement : unanimity Source: http://www.merriam-webster.com/ con sen sus noun \ kən-ˈsen(t)-səs

More information

Internet Technology 2/7/2013

Internet Technology 2/7/2013 Sample Client-Server Program Internet Technology 02r. Programming with Sockets Paul Krzyzanowski Rutgers University Spring 2013 To illustrate programming with TCP/IP sockets, we ll write a small client-server

More information

Decorator Pattern. Decorator Pattern. Decorator Problems Decorator Examples Proxy Pattern. Motivation Structure Decorator vs Inheritance vs Strategy

Decorator Pattern. Decorator Pattern. Decorator Problems Decorator Examples Proxy Pattern. Motivation Structure Decorator vs Inheritance vs Strategy Decorator Pattern Decorator Pattern Motivation Structure Decorator vs Inheritance vs Strategy Decorator Problems Decorator Examples Proxy Pattern 1 Vibrating & Skin Phones 2 Implementation with Inheritance

More information

CS September 2017

CS September 2017 Machine vs. transport endpoints IP is a network layer protocol: packets address only the machine IP header identifies source IP address, destination IP address Distributed Systems 01r. Sockets Programming

More information

Sockets(for(Server( SKET4623(

Sockets(for(Server( SKET4623( ! Reading(Material(7(( Sockets(for(Server( SKET4623( ABSTRACT( Socket(is(a(connection(between(two(hosts.(Java s(socket(class(is(used( by(both(client(and(server.(client(uses(socket(to(communicate(with(other(

More information

Socket 101 Excerpt from Network Programming

Socket 101 Excerpt from Network Programming Socket 101 Excerpt from Network Programming EDA095 Nätverksprogrammering Originals by Roger Henriksson Computer Science Lund University Java I/O Streams Stream (swe. Ström) - A stream is a sequential ordering

More information

Introduction to Java.net Package. CGS 3416 Java for Non Majors

Introduction to Java.net Package. CGS 3416 Java for Non Majors Introduction to Java.net Package CGS 3416 Java for Non Majors 1 Package Overview The package java.net contains class and interfaces that provide powerful infrastructure for implementing networking applications.

More information

I.-C. Lin, Assistant Professor. Textbook: Operating System Concepts 8ed CHAPTER 10: FILE SYSTEM

I.-C. Lin, Assistant Professor. Textbook: Operating System Concepts 8ed CHAPTER 10: FILE SYSTEM I.-C. Lin, Assistant Professor. Textbook: Operating System Concepts 8ed CHAPTER 10: FILE SYSTEM Chapter 10: File System File Concept Access Methods Directory Structure File-System Mounting File Sharing

More information

New IO (NIO) SYSTEM SOFTWARE 1

New IO (NIO) SYSTEM SOFTWARE 1 New IO (NIO) SYSTEM SOFTWARE 1 New IO (NIO) With NIO und NIO.2 there exist new classes for file management and input and output Packages java.nio.files Path and Files for file management java.nio.channel

More information

EI 338: Computer Systems Engineering (Operating Systems & Computer Architecture)

EI 338: Computer Systems Engineering (Operating Systems & Computer Architecture) EI 338: Computer Systems Engineering (Operating Systems & Computer Architecture) Dept. of Computer Science & Engineering Chentao Wu wuct@cs.sjtu.edu.cn Download lectures ftp://public.sjtu.edu.cn User:

More information

Java Development: Do s and Don ts

Java Development: Do s and Don ts Java Development: Do s and Don ts 1 Overview Asynchronous networking Data copies Connection management Logging 2 ASL Project 2016: Middleware for different replication modes Middleware op SET/DEL GET Memcached

More information

New Features Overview

New Features Overview Features pf JDK 7 New Features Overview Full List: http://docs.oracle.com/javase/7/docs/webnotes/adoptionguide/index.html JSR 334: Small language enhancements (Project Coin) Concurrency and collections

More information

public class MyThread extends Thread { try { private Shared theshared; threada.join(); threadb.join();

public class MyThread extends Thread { try { private Shared theshared; threada.join(); threadb.join(); Race Conditions Consider the following Java code int localdata = theshared.getdata(); localdata++; theshared.setdata(localdata); After executing this code what value is stored in Shared.data? public class

More information

CPSC 441 Tutorial TCP Server. Department of Computer Science University of Calgary

CPSC 441 Tutorial TCP Server. Department of Computer Science University of Calgary CPSC 441 Tutorial TCP Server Department of Computer Science University of Calgary TCP Socket Client Server Connection Request Server Listening on welcoming socket Client Socket Server Socket Data Simple

More information

Chapter 10: File System

Chapter 10: File System Chapter 10: File System Chapter 10: File-System File Concept File attributes, File operations, File types, File structures Access Methods Directory Structure File-System Mounting File Sharing Protection

More information

CS455: Introduction to Distributed Systems [Spring 2018] Dept. Of Computer Science, Colorado State University

CS455: Introduction to Distributed Systems [Spring 2018] Dept. Of Computer Science, Colorado State University CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [HDFS] Circumventing The Perils of Doing Too Much Protect the namenode, you must, from failure What s not an option? Playing it by ear Given the volumes, be

More information

Dept. Of Computer Science, Colorado State University

Dept. Of Computer Science, Colorado State University CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [HDFS] Circumventing The Perils of Doing Too Much Protect the namenode, you must, from failure What s not an option? Playing it by ear Given the volumes, be

More information

Chapter 10: File-System Interface

Chapter 10: File-System Interface Chapter 10: File-System Interface Chapter 10: File-System Interface File Concept Access Methods Directory Structure File-System Mounting File Sharing Protection 10.2 Silberschatz, Galvin and Gagne 2005

More information

Web Server Project. Tom Kelliher, CS points, due May 4, 2011

Web Server Project. Tom Kelliher, CS points, due May 4, 2011 Web Server Project Tom Kelliher, CS 325 100 points, due May 4, 2011 Introduction (From Kurose & Ross, 4th ed.) In this project you will develop a Web server in two steps. In the end, you will have built

More information

CS 378 Big Data Programming

CS 378 Big Data Programming CS 378 Big Data Programming Lecture 9 Complex Writable Types AVRO, Protobuf CS 378 - Fall 2017 Big Data Programming 1 Review Assignment 4 WordStaQsQcs using Avro QuesQons/issues? MRUnit and AVRO AVRO keys,

More information

Chapter 11: File-System Interface

Chapter 11: File-System Interface Chapter 11: File-System Interface Chapter 11: File-System Interface File Concept Access Methods Disk and Directory Structure File-System Mounting File Sharing Protection Objectives To explain the function

More information

Chapter 10: File-System Interface. File Concept Access Methods Directory Structure File-System Mounting File Sharing Protection

Chapter 10: File-System Interface. File Concept Access Methods Directory Structure File-System Mounting File Sharing Protection Chapter 10: File-System Interface File Concept Access Methods Directory Structure File-System Mounting File Sharing Protection Objectives To explain the function of file systems To describe the interfaces

More information

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages References Exceptions "Handling Errors with Exceptions", Java tutorial http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html CSE 413, Autumn 2005 Programming Languages http://www.cs.washington.edu/education/courses/413/05au/

More information

Agenda: Discussion Week 7. May 11, 2009

Agenda: Discussion Week 7. May 11, 2009 Agenda: Discussion Week 7 Method signatures Static vs. instance compareto Exceptions Interfaces 2 D arrays Recursion varargs enum Suggestions? May 11, 2009 Method signatures [protection] [static] [return

More information

Chapter 11: File-System Interface

Chapter 11: File-System Interface Chapter 11: File-System Interface Silberschatz, Galvin and Gagne 2013 Chapter 11: File-System Interface File Concept Access Methods Disk and Directory Structure 11.2 Silberschatz, Galvin and Gagne 2013

More information

CS5233 Components Models and Engineering

CS5233 Components Models and Engineering Prof. Dr. Th. Letschert CS5233 Components Models and Engineering - Komponententechnologien Master of Science (Informatik) Working with Jars (and other files using NIO) Seite 1 Jars http://download.oracle.com/javase/tutorial/deployment/jar/index.html

More information

Basic I/O - Stream. Java.io (stream based IO) Java.nio(Buffer and channel-based IO)

Basic I/O - Stream. Java.io (stream based IO) Java.nio(Buffer and channel-based IO) I/O and Scannar Sisoft Technologies Pvt Ltd SRC E7, Shipra Riviera Bazar, Gyan Khand-3, Indirapuram, Ghaziabad Website: www.sisoft.in Email:info@sisoft.in Phone: +91-9999-283-283 I/O operations Three steps:

More information

COSC 6397 Big Data Analytics. Distributed File Systems (II) Edgar Gabriel Spring HDFS Basics

COSC 6397 Big Data Analytics. Distributed File Systems (II) Edgar Gabriel Spring HDFS Basics COSC 6397 Big Data Analytics Distributed File Systems (II) Edgar Gabriel Spring 2017 HDFS Basics An open-source implementation of Google File System Assume that node failure rate is high Assumes a small

More information

M257 Past Paper Oct 2008 Attempted Solution

M257 Past Paper Oct 2008 Attempted Solution M257 Past Paper Oct 2008 Attempted Solution Part 1 Question 1 A version of Java is a particular release of the language, which may be succeeded by subsequent updated versions at a later time. Some examples

More information

Data Structures. 03 Streams & File I/O

Data Structures. 03 Streams & File I/O David Drohan Data Structures 03 Streams & File I/O JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN 0132162709 2012 Pearson Education, Inc., Upper Saddle River, NJ.

More information

MEAP Edition Manning Early Access Program Vert.x in Action Version 1

MEAP Edition Manning Early Access Program Vert.x in Action Version 1 MEAP Edition Manning Early Access Program Vert.x in Action Version 1 Copyright 2018 Manning Publications For more information on this and other Manning titles go to www.manning.com welcome Thank you for

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

Chapter 11: File-System Interface. Operating System Concepts 9 th Edition

Chapter 11: File-System Interface. Operating System Concepts 9 th Edition Chapter 11: File-System Interface Silberschatz, Galvin and Gagne 2013 Chapter 11: File-System Interface File Concept Access Methods Disk and Directory Structure File-System Mounting File Sharing Protection

More information

Chapter 11: File-System Interface

Chapter 11: File-System Interface Chapter 11: File-System Interface Silberschatz, Galvin and Gagne 2013! Chapter 11: File-System Interface File Concept" Access Methods" Directory Structure" File-System Mounting" File Sharing" Protection"

More information

Polymorphism & A Few Java Interfaces

Polymorphism & A Few Java Interfaces Polymorphism & A Few Java Interfaces Rick Mercer 3-1 Outline w Describe Polymorphism w Show a few ways that interfaces are used Respond to user interaction with a GUI with ActionListener Compare objects

More information

Chapter 10: File-System Interface. Operating System Concepts 8 th Edition

Chapter 10: File-System Interface. Operating System Concepts 8 th Edition Chapter 10: File-System Interface Silberschatz, Galvin and Gagne 2009 Chapter 10: File-System Interface File Concept Access Methods Directory Structure File-System Mounting File Sharing Protection 10.2

More information

Chapter 11: File-System Interface. Long-term Information Storage. File Structure. File Structure. File Concept. File Attributes

Chapter 11: File-System Interface. Long-term Information Storage. File Structure. File Structure. File Concept. File Attributes Chapter 11: File-System Interface File Concept Access Methods Directory Structure File System Mounting File Sharing Protection Long-term Information Storage 1. Must store large amounts of data 2. Information

More information

Copyright 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13

Copyright 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 1 JDK7 In Action Using New Core Platform Features In Real Code Joe Darcy Mike Duigou Stuart Marks Oracle JDK Team @jddarcy @mjduigou @stuartmarks 2 Program Agenda Project Coin Small Language Features NIO.2

More information

Scalable IO in Java Doug Lea State University of New York at Oswego

Scalable IO in Java Doug Lea State University of New York at Oswego Scalable IO in Java Doug Lea State University of New York at Oswego dl@cs.oswego.edu Outline Scalable network services Event-driven processing Reactor pattern Basic version Multithreaded versions Other

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1(c): Java Basics (II) Lecture Contents Java basics (part II) Conditions Loops Methods Conditions & Branching Conditional Statements A

More information

Computer 2 App1. App3 API Library. App3. API Library. Local Clipboard

Computer 2 App1. App3 API Library. App3. API Library. Local Clipboard System Programming (MEEC/MEAer) Project Assignment 2016/2017 In this project the students will implement a simple distributed clipboard. Applications can copy and past to/from the distributed clipboard

More information

CS 11 java track: lecture 6

CS 11 java track: lecture 6 CS 11 java track: lecture 6 This week: networking basics Sockets Vectors parsing strings what is networking? the network: world-wide web of interconnected computers "the internet" networking: programming

More information

Building Java Programs. Inheritance and Polymorphism

Building Java Programs. Inheritance and Polymorphism Building Java Programs Inheritance and Polymorphism Input and output streams stream: an abstraction of a source or target of data 8-bit bytes flow to (output) and from (input) streams can represent many

More information

CS2: Debugging in Java

CS2: Debugging in Java CS2: Debugging in Java 1. General Advice Jon Cook (LFCS) April 2003 Debugging is not always easy. Some bugs can take a long time to find. Debugging concurrent code can be particularly difficult and time

More information

Introduction. System Overview. APPLICATION NOTE 709 Adding An External File System to TINI

Introduction. System Overview. APPLICATION NOTE 709 Adding An External File System to TINI Maxim > App Notes > MICROCONTROLLERS Keywords: TINI, Tiny Internet Interfaces, external file system, mountable file system Aug 27, 2002 APPLICATION NOTE 709 Adding An External File System to TINI Abstract:

More information

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. CSE 142, Summer 2002 Computer Programming 1. Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 1 Reading Readings and References»

More information

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1. Readings and References Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ Reading» Chapter 18, An Introduction to Programming and Object Oriented

More information

Prelim One Solution. CS211 Fall Name. NetID

Prelim One Solution. CS211 Fall Name. NetID Name NetID Prelim One Solution CS211 Fall 2005 Closed book; closed notes; no calculators. Write your name and netid above. Write your name clearly on each page of this exam. For partial credit, you must

More information

0.8.0 SimpleConsumer Example

0.8.0 SimpleConsumer Example 0.8.0 SimpleConsumer Example Using SimpleConsumer Why use SimpleConsumer? The main reason to use a SimpleConsumer implementation is you want greater control over partition consumption than Consumer Groups

More information

CS11 Java. Fall Lecture 4

CS11 Java. Fall Lecture 4 CS11 Java Fall 2014-2015 Lecture 4 Java File Objects! Java represents files with java.io.file class " Can represent either absolute or relative paths! Absolute paths start at the root directory of the

More information

CS 351 Week 15. Course Review

CS 351 Week 15. Course Review CS 351 Week 15 Course Review Objectives: 1. To review the contents from different weeks. 2. To have a complete understanding of important concepts from different weeks. Concepts: 1. Important Concepts

More information

Object-Oriented Programming. Topic 2: Fundamental Programming Structures in Java

Object-Oriented Programming. Topic 2: Fundamental Programming Structures in Java Electrical and Computer Engineering Object-Oriented Topic 2: Fundamental Structures in Java Maj Joel Young Joel.Young@afit.edu 8-Sep-03 Maj Joel Young Java Identifiers Identifiers Used to name local variables

More information

File-System Interface

File-System Interface File-System Interface Chapter 10: File-System Interface File Concept Access Methods Directory Structure File-System Mounting File Sharing Protection Objectives To explain the function of file systems To

More information

JAVA NOTES DATA STRUCTURES AND ALGORITHMS

JAVA NOTES DATA STRUCTURES AND ALGORITHMS 179 JAVA NOTES DATA STRUCTURES AND ALGORITHMS Terry Marris August 2001 19 RANDOM ACCESS FILES 19.1 LEARNING OUTCOMES By the end of this lesson the student should be able to picture a random access file

More information

CS Programming I: File Input / Output

CS Programming I: File Input / Output CS 200 - Programming I: File Input / Output Marc Renault Department of Computer Sciences University of Wisconsin Madison Fall 2017 TopHat Sec 3 (PM) Join Code: 719946 TopHat Sec 4 (AM) Join Code: 891624

More information

CSCD433/533 Advanced Networks Winter 2017 Lecture 13. Raw vs. Cooked Sockets

CSCD433/533 Advanced Networks Winter 2017 Lecture 13. Raw vs. Cooked Sockets CSCD433/533 Advanced Networks Winter 2017 Lecture 13 Raw vs. Cooked Sockets Introduction Better Understand the Protocol Stack Use Raw Sockets So far, sockets in Java either TCP or UDP based In fact, Java

More information

Modbat. A Model-Based API Tester for Event-Driven Systems

Modbat. A Model-Based API Tester for Event-Driven Systems Modbat A Model-Based API Tester for Event-Driven Systems Cyrille Artho, Armin Biere, Masami Hagiya Eric Platon, Martina Seidl, Yoshinori Tanabe, Mitsuharu Yamamoto HVC 2013 Haifa Verification Conference

More information

Chapter 2 Applications and

Chapter 2 Applications and Chapter 2 Applications and Layered Architectures Sockets Socket API API (Application Programming Interface) Provides a standard set of functions that can be called by applications Berkeley UNIX Sockets

More information

Chapter 11: File System Interface

Chapter 11: File System Interface COP 4610: Introduction to Operating Systems (Spring 2016) Chapter 11: File System Interface Zhi Wang Florida State University Content File concept Access methods Directory structure File-system mounting

More information