WRITING DATA TO A BINARY FILE



Similar documents
CS 1302 Ch 19, Binary I/O

The Java I/O System. Binary I/O streams (ascii, 8 bits) The decorator design pattern Character I/O streams (Unicode, 16 bits)

INPUT AND OUTPUT STREAMS

What is an I/O Stream?

JAVA - FILES AND I/O

D06 PROGRAMMING with JAVA

public static void main(string[] args) { System.out.println("hello, world"); } }

Introduction to Java

Object-Oriented Programming in Java

AVRO - SERIALIZATION

File I/O - Chapter 10. Many Stream Classes. Text Files vs Binary Files

Files and input/output streams

Creating a Simple, Multithreaded Chat System with Java

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.

Java Network Programming. The java.net package contains the Socket class. This class speaks TCP (connection-oriented protocol).

Java Interview Questions and Answers

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

Building a Multi-Threaded Web Server

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

CS 111 Classes I 1. Software Organization View to this point:

Today s Outline. Computer Communications. Java Communications uses Streams. Wrapping Streams. Stream Conventions 2/13/2016 CSE 132

Chapter 2 Introduction to Java programming

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. AVRO Tutorial

Programming in Java

Using Files as Input/Output in Java 5.0 Applications

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

CS506 Web Design and Development Solved Online Quiz No. 01

Learning Outcomes. Networking. Sockets. TCP/IP Networks. Hostnames and DNS TCP/IP

Java from a C perspective. Plan

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

An Overview of Java. overview-1

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Decorator Pattern [GoF]

Quick Introduction to Java

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Input / Output Framework java.io Framework

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Continuous Integration Part 2

Stream Classes and File I/O

Explain the relationship between a class and an object. Which is general and which is specific?

This example illustrates how to copy contents from one file to another file. This topic is related to the I/O (input/output) of

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Crash Course in Java

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

AP Computer Science Java Subset

Event-Driven Programming

Lesson: All About Sockets

Mail User Agent Project

Introduction to Java. CS 3: Computer Programming in Java

AP Computer Science File Input with Scanner

Chapter 2: Elements of Java

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

Part I. Multiple Choice Questions (2 points each):

Java Programming Fundamentals

AWS Encryption SDK. Developer Guide

Principles of Software Construction: Objects, Design, and Concurrency. Design Case Study: Stream I/O Some answers. Charlie Garrod Jonathan Aldrich

13 File Output and Input

Application Development with TCP/IP. Brian S. Mitchell Drexel University

Chapter 10. A stream is an object that enables the flow of data between a program and some I/O device or file. File I/O

Lecture J - Exceptions

Question1-part2 What undesirable consequences might there be in having too long a DNS cache entry lifetime?

C++ INTERVIEW QUESTIONS

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Communicating with a Barco projector over network. Technical note

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

Introduction to Java. Module 12: Networking (Java Sockets) Prepared by Costantinos Costa for EPL 233. ΕΠΛ233 Αντικειμενοστρεφής Προγραμματισμός 1

Transport layer protocols. Message destination: Socket +Port. Asynchronous vs. Synchronous. Operations of Request-Reply. Sockets

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

1 of 1 24/05/ :23 AM

Chapter 1 Java Program Design and Development

CS 106 Introduction to Computer Science I

Readings and References. Topic #10: Java Input / Output. "Streams" are the basic I/O objects. Input & Output. Streams. The stream model A-1.

Text file I/O and simple GUI dialogues

Homework/Program #5 Solutions

Remote Method Invocation

Network/Socket Programming in Java. Rajkumar Buyya

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

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

Lecture 5: Java Fundamentals III

CS 121 Intro to Programming:Java - Lecture 11 Announcements

Computing Concepts with Java Essentials

Zebra and MapReduce. Table of contents. 1 Overview Hadoop MapReduce APIs Zebra MapReduce APIs Zebra MapReduce Examples...

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Java Crash Course Part I

Socket Programming in Java

Comparing the Effectiveness of Penetration Testing and Static Code Analysis

Pemrograman Dasar. Basic Elements Of Java

Objectives. Streams and File I/O. Objectives, cont. Outline. I/O Overview. Streams

NETWORK PROGRAMMING IN JAVA USING SOCKETS

J a v a Quiz (Unit 3, Test 0 Practice)

Transcription:

WRITING DATA TO A BINARY FILE TEXT FILES VS. BINARY FILES Up to now, we have looked at how to write and read characters to and from a text file. Text files are files that contain sequences of characters. Binary files, on the other hand, are files that contain sequences of binary digits. Unlike text files which are designed to be read by human beings, binary files are designed to be read by programs. The following are just some of the advantages of using binary files versus text files: One of the biggest advantages of using binary files over text files is that they are more efficient to process than text files. Unlike a text file whose characters need to be converted into binary, a binary file is already in stored in a format that the computer understands. A binary file is much smaller than a text file that contains an equivalent amount of data. Some kinds of data cannot be easily represented as characters (e.g. the bytecode of a Java class file or the code stored in an executable file). THE CLASSES USED TO WRITE TO A BINARY FILE To write data to a binary file, you must use the following classes: 1. FileOutputStream The FileOutputStream class connects to a File object and creates an output stream that can write to the file. However, this output stream can only write raw bytes to the file; it doesn t know how to write Integer, Double, or String values. The following table outlines the constructors for the FileOutputStream class: FileOutputStream(File f) FileOutputStream(File f, boolean append) FileOutputStream(String path) Creates a file writer from the file. Throws Creates a file writer from the file. If the second parameter is true, data is added to the end of the file if the file already exists. Throws FileNotFoundException if an error occurs. Creates a file writer from the specified pathname. Throws Writing Data to a Binary File Page 1 of 5

FileOutputStream(String path, boolean append) Creates a file writer from the specified pathname. If the second parameter is true, data is added to the end of the file if the file already exists. Throws 2. BufferedOutputStream The BufferedOutputStream class connects to a FileOutputStream and adds output buffering. Without the buffer, in other words, data is written one character at a time. This class lets the program accumulate data in a buffer and writes the data only when the buffer is filled up or when the program requests that the data be written. BufferedOutputStream (OutputStream out) Creates a buffered output stream for the specified stream. Typically you pass this constructor a FileOutputStream object. 3. DataOutputStream This class adds the ability to write primitive data types and strings to a stream. DataOutputStream (OutputStream out) Creates a data output stream for the specified output stream. The following table outlines some of the methods included in the DataOutputStream class: METHODS void close() void flush() int size() void writeboolean(boolean value) void writechar(char value) void writedouble(double value) void writeint(int value) Closes the file. Writes the contents of the buffer to disk. Returns the number of bytes written to the file. Writes a boolean value to the output stream. Throws Writes a char value to the output stream. Throws Writes a double value to the output stream. Throws Writes an int value to the output stream. Throws Writing Data to a Binary File Page 2 of 5

void writelong(long value) void writeutf(string value) Writes a long value to the output stream. Throws Writes a string stored in UTF format to the output stream. Throws EOFException, IOException, and UTFDataFormatException errors. CREATING A DataOutputStream OBJECT You can create a DataOutputStream in one of two ways. The first method uses nested constructors to create each of the required objects: File f = new File( demo.dat ); Alternatively, you can create each object as a separate constructor as follows: File f = new File( demo.dat ); FileOutputStream fos = new FileOutputStream(f); BufferedOutputStream bos = new BufferedOutputStream(fos); DataOutputStream out = new DataOutputStream(bos); Since the FileOutputStream throws an exception if an error occurs, you will need to instantiate the FileOutputStream object within a try catch statement as we did with the FileWriter class: import java.io.*; import javax.swing.*; public class Demo public static void main(string[] args) // Declare and initialize File object File f = new File("test.dat"); try // Declare and initialize DataOutputStream object catch (IOException e) // Output error message if exception is thrown JOptionPane.showMessageDialog(null, e.getmessage() +!, Error, JOptionPane.ERROR_MESSAGE); Writing Data to a Binary File Page 3 of 5

WRITING TO A BINARY STREAM Once you have successfully created a DataOutputStream object, writing data to a binary file is simply a matter of calling the various methods included in the DataOutputStream class to write different data types to the file. The following example prompts the user for his/her name and age and writes the data to a file called info.dat: import java.io.*; import javax.swing.*; public class Demo public static void main(string[] args) // Declare and intialize File object File f = new File("info.dat"); try // Declare and initialize DataOutputStream object // Prompt user for name and age String name = JOptionPane.showInputDialog(null, "Please enter your name:", "Binary File Demo", JOptionPane.INFORMATION_MESSAGE); int age = Integer.parseInt(JOptionPane.showInputDialog (null, "Please enter your age:", "Binary File Demo", JOptionPane.INFORMATION_MESSAGE)); // Write data to file out.writeutf(name); out.writeint(age); // Close DataOutputStream object out.close(); catch (IOException e) // Output error message if exception is thrown JOptionPane.showMessageDialog(null, e.getmessage() + "!", "Error!", JOptionPane.ERROR_MESSAGE); Writing Data to a Binary File Page 4 of 5

If the user enters Jack Black as his name and age 40, this is what the binary file would look like when opened in Notepad: Writing Data to a Binary File Page 5 of 5