View RSS Feed

penguinCoder

File Input Output Cheat Sheet

Rate this Entry
by , 10-30-2012 at 04:18 AM (2732 Views)
File Input Output Cheat Sheet

Importing Libraries
The primary library that deals with files:
Java Code:
import java.io.File;
The library that deals with writing to files:
Java Code:
import java.io.PrintWriter;

FYI
If there is more then one type of information that is being transferred to or from a file, it is usually best to use a record; IMO.


Writing to a File

Declare and Allocate a File Instance
Java Code:
File fileVarName = new File("path/to/file.txt");
This file path is based on the Linux File Systems, Windows users will have to specify c:\path\file.txt

Declare and Allocate a PrintWriter Instance
Java Code:
PrintWriter printVarName = new PrintWriter(fileVarName);
[b]Writing to the File[b]
Java Code:
printVarName.println("penguinCoder");
printVarName.println(848.2884);
printVarName.println(false);
De-Allocating the PrintWriter Instance
Java Code:
printVarName.close();


Reading From a File

Declare and Allocate a File Instance
Java Code:
File fileVarName = new File("path/to/file.txt");
This file path is based on the Linux File Systems, Windows users :( will have to specify c:\path\file.txt

Declare and Allocate a Scanner Instance
Java Code:
Scanner keyboard = new Scanner(fileVarName);
Checking if there is a next line to be read
Returns true if there is another line, returns false if it is the final line.
Java Code:
keyboard.hasNext();
Reading the next line
Java Code:
keyboard.nextLine();
Reading the next Integer
Java Code:
keyboard.nextInt();
Reading the next Double
Java Code:
keyboard.nextDouble();
Reading the next String
Java Code:
keyboard.next();
Reading the next Character
Java Code:
keyboard.next().charAt(0);
De-Allocating the Scanner Instance
Java Code:
keyboard.close();


Checking if File Exists
Java Code:
File fileVarName = new File("file/path/name.txt");

if( fileVarName.exists() ){
  ...code...
}
else
  System.out.println("That file does not exist");


Deleting a File
Java Code:
File fileVarName = new File("file/path/name.txt");

if( fileVarName.exists() ){
  fileVarName.delete();
  System.out.println(fileVarName + " has been deleted.");
}
else
  System.out.println("That file does not exist");

Submit "File Input Output Cheat Sheet" to Facebook Submit "File Input Output Cheat Sheet" to Digg Submit "File Input Output Cheat Sheet" to del.icio.us Submit "File Input Output Cheat Sheet" to StumbleUpon Submit "File Input Output Cheat Sheet" to Google

Comments