📕
Dan Fitz's Notes
  • README
  • Ai
    • Supervised Machine Learning
      • Introduction To Machine Learning
      • Regression With Multiple Input Variables
      • Classification
  • Csharp
    • C Sharp Advanced
      • Generics
      • Delegates
      • Lambda Expressions
      • Events
    • C Sharp Fundamentals
      • Intro To C
      • Primitive Types And Expressions
      • Non Primitive Types
      • Control Flow
      • Arrays And Lists
      • Working With Dates
      • Working With Text
      • Working With Files
      • Debugging Applications
    • C Sharp Intermediate
      • Classes
      • Association Between Classes
      • Inheritance
      • Polymorphism
      • Interfaces
  • Java
    • Inheritance Data Structures Java
      • Inheritance Polymorphism Using Overriding And Access Modifiers
      • Abstract Classes And Debugging
      • File I O And Exceptions
      • Collections Maps And Regular Expressions
    • Intro To Java
      • Introduction To Java Classes And Eclipse
      • Unit Testing Arrays And Array Lists
      • Static Variables Methods And Polymorphism Using Overloading
  • Javascript
    • Algorithms Data Structures
      • Big O Notation
      • Analyzing Performance Of Arrays And Objects
      • Problem Solving Approach
      • Problem Solving Patterns
      • Recursion
      • Searching Algorithms
      • Bubble Selection And Insertion Sort
      • Merge Sort
      • Quick Sort
      • Radix Sort
      • Data Structures Introduction
      • Singly Linked Lists
      • Doubly Linked Lists
      • Stacks And Queues
      • Binary Search Trees
      • Tree Traversal
      • Binary Heaps
    • Complete Nodejs
      • Understanding Node.js
      • REST AP Is And Mongoose
      • API Authentication And Security
      • Node.js Module System
      • File System And Command Line Args
      • Debugging Node.js
      • Asynchronous Node.js
      • Web Servers
      • Accessing API From Browser
      • Application Deployment
      • Mongo DB And Promises
    • Complete React Native
      • Working With Content
      • Building Lists
      • Navigating Users Between Screens
      • State Management
      • Handling Screen Layout
      • Setting Up An App
      • More On Navigation
      • Advanced Statement Management With Context
      • Building A Custom Express API
      • In App Authentication
    • Epic React
      • React Fundamentals
      • React Hooks
      • Advanced React Hooks
      • Advanced React Patterns
      • React Performance
    • Fireship Firestore
      • Firestore Queries And Data Modeling Course
      • Model Relational Data In Firestore No SQL
    • Functional Light Javascript
      • Intro
      • Function Purity
      • Argument Adapters
      • Point Free
      • Closure
      • Composition
      • Immutability
      • Recursion
      • List Operations
      • Transduction
      • Data Structure Operations
      • Async
    • Js Weird Parts
      • Execution Contexts And Lexical Environments
      • Types And Operators
      • Objects And Functions
      • Object Oriented Java Script And Prototypal Inheritance
      • Defining Objects
    • Mastering Chrome Dev Tools
      • Introduction
      • Editing
      • Debugging
      • Networking
      • Auditing
      • Node.js Profiling
      • Performance Monitoring
      • Image Performance
      • Memory
    • React Complete Guide
      • What Is React
      • React Basics
      • Rendering Lists And Conditionals
      • Styling React Components
      • Debugging React Apps
      • Component Deep Dive
      • Building A React App
      • Reaching Out To The Web
      • Routing
    • React Testing
      • Intro To Jest Enzyme And TDD
      • Basic Testing
      • Redux Testing
      • Redux Thunk Testing
    • Serverless Bootcamp
      • Introduction
      • Auction Service Setup
      • Auction Service CRUD Operations
      • Auction Service Processing Auctions
    • Testing Javascript
      • Fundamentals Of Testing
      • Static Analysis Testing
      • Mocking Fundamentals
      • Configuring Jest
      • Test React Components With Jest And React Testing Library
    • Typescript Developers Guide
      • Getting Started With Type Script
      • What Is A Type System
      • Type Annotations In Action
      • Annotations With Functions And Objects
      • Mastering Typed Arrays
      • Tuples In Type Script
      • The All Important Interface
      • Building Functionality With Classes
    • Web Performance With Webpack
      • Intro
      • Code Splitting
      • Module Methods Magic Comments
  • Other
    • Algo Expert
      • Defining Data Structures And Complexity Analysis
      • Memory
      • Big O Notation
      • Logarithm
      • Arrays
      • Linked Lists
      • Hash Tables
      • Stacks And Queues
      • Strings
      • Graphs
      • Trees
    • Aws Solutions Architect
      • AWS Fundamentals IAM EC 2
    • Fundamentals Math
      • Numbers And Negative Numbers
      • Factors And Multiples
      • Fractions
    • Mysql Bootcamp
      • Overview And Installation
      • Creating Databases And Tables
      • Inserting Data
      • CRUD Commands
      • The World Of String Functions
      • Refining Our Selections
      • The Magic Of Aggregate Functions
    • Random Notes
      • Understanding React Hooks
  • Python
    • Data Analysis Using Python
      • Loading Querying And Filtering Data Using The Csv Module
      • Loading Querying Joining And Filtering Data Using Pandas
      • Summarizing And Visualizing Data
    • Intro To Python
      • Course Introduction Intro To Programming And The Python Language Variables Conditionals Jupyter Notebook And IDLE
      • Intro To Lists Loops And Functions
      • More With Lists Strings Tuples Sets And Py Charm
      • Dictionaries And Files
Powered by GitBook
On this page
  • File I/O
  • Reading with FileReader and BufferedReader
  • Reading with Scanner
  • Writing with FileWriter and PrintWriter
  • Writing with FileWriter and BufferedWriter
  • Exceptions
  • Try, catch, finally pattern
  • Passing the buck
  1. Java
  2. Inheritance Data Structures Java

File I O And Exceptions

File I/O

Java I/O works via a stream: a connection to a source of data. This connection could be to

  • Files

  • Keyboard input

  • Etc.

To perform I/O at a high-level, these are the steps:

  1. import java.io.*;

  2. Open a stream

  3. Use the stream (read, write, or read-write)

  4. Close the stream

Reading with FileReader and BufferedReader

// 1. Import
import java.io.*;

// 2. Open stream
File myFile = new File(pathToFile);
FileReader fileReader = new FileReader(myFile);
BufferedReader bufferedReader = new BufferedReader(fileReader); // buffered version

// 3. Use stream
String s = bufferedReader.readLine(); // returns null if nothing more to read

// 4. Close stream
fileReader.close();
bufferedReader.close();

Reading with Scanner

// 1. Import
import java.io.*;

// 2. Open stream
File myFile = new File(pathToFile);
Scanner scanner = new Scanner(myFile);

// 3. Use stream
scanner.next(); // next string
scanner.nextBoolean(); // next boolean
scanner.nextInt(); // next int
scanner.hasNext(); // check if there's a next string!
scanner.hasNextBoolean(); // check if there's a next boolean!
scanner.hasNextInt(); // check if there's a next int!

// Best practice is to check before getting next
if (scanner.hasNextInt()) {
  int i = scanner.nextInt();
}

// 4. Close stream
scanner.close();

Writing with FileWriter and PrintWriter

// 1. Import
import java.io.*;

// 2. Open stream
File myFile = File(pathToFile);
boolean append = true; // decides if writing to file appends to end or not
FileWriter fw = new FileWriter(myFile, append);
PrintWriter pw = new PrintWriter(fw);

// 3. Use stream
pw.println("Dear diary,"); // on new line
pw.print("Uh oh"); // on same line

// IMPORTANT: Force data to be written to file
pw.flush();

// 4. Close stream
fw.close();
pw.close();

Writing with FileWriter and BufferedWriter

// 1. Import
import java.io.*;

// 2. Open stream
File myFile = File(pathToFile);
boolean append = true; // decides if writing to file appends to end or not
FileWriter fw = new FileWriter(myFile, append);
BufferedWriter bw = new BufferedWriter(fw); // uses buffering for efficiency

// 3. Use stream
bw.write("Dear diary,");
bw.write("\n");
bw.write("Uh oh");

// IMPORTANT: Force data to be written to file
bw.flush();

// 4. Close stream
fw.close();
bw.close();

Exceptions

Errors are actual bugs in your program:

  • Going out of bounds of array

  • Trying to use a null reference

Exceptions, on the other hand, have to do with causes outside of your program:

  • Trying to read a file that doesn't exist

  • Running out of memory

Because exceptions aren't necessarily your fault, often times the best thing you can do is write your code in such a way that catches and handles those exceptions.

Try, catch, finally pattern

Java has a control flow for catching and handling exceptions:

try {
  // Do your normal code
} catch (Exception1 e1) {
  // Handle one kind of exception 
} catch (Exception2 e2) {
  // Handle another kind of exception
} finally {
  // This runs at the end no matter what
  // (whether code runs successfully or exception occurs)
}

Note: The finally block even runs when you provide a return statement in the other blocks!

Passing the buck

Sometimes you don't want to be handling the exception yourself because you want the caller of the method to handle the exception themselves.

What you can do when defining a method that can generate an exception is to include a throws keyword:

void openFile(File file) throws IOException {
  FileReader fileReader = new FileReader(file);
  // ...
}
PreviousAbstract Classes And DebuggingNextCollections Maps And Regular Expressions

Last updated 2 years ago