Java - I/O (Input/Output), Binary, RAF, Object Serialization - Code / Coding Examples

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

File Writer - class, methods

*1 public void write(int c) throws IOException* Writes a single character. *2 public void write(char [] c, int offset, int len)* Writes a portion of an array of characters starting from offset and with a length of len. *3 public void write(String s, int offset, int len)* Write a portion of a String starting from offset and with a length of len.

Binary & Text -> TEXT FILES -> PrintWriter (appending to a text file)

*outputStreamName = new PrintWriter(new * *FileOutputStream(FileName, true));*

Binary & Text -> TEXT FILES -> close the stream

*outputStreamName.close();*

File Reader - using File Reader class

// Creates a new FileReader, given the // File to read from. FileReader(File file) // Creates a new FileReader, given the // FileDescriptor to read from. FileReader(FileDescriptor fd) // Creates a new FileReader, given the // name of the file to read from. FileReader(String fileName) // Java Program to illustrate reading from // FileReader using FileReader import java.io.*; public class ReadingFromFile { public static void main(String[] args) throws Exception { // pass the path to the file as a parameter FileReader fr = new FileReader("C:\\Users\\pankaj\\Desktop\\test.txt"); int i; while ((i=fr.read()) != -1) System.out.print((char) i); } }

FileOutputStream

// File output stream *FileOutputStream fileByteStream = null; * // Output stream *PrintWriter outFS = null; * // Try to open file * fileByteStream =* * new FileOutputStream("myoutfile.txt");* * outFS = new PrintWriter(fileByteStream);* // File is open and valid if we got this far // Can now write to file *outFS.println("Hello");* *outFS.println("1 2 3");* *outFS.flush();*

File Reader - using Scanner class, without loops

// Java Program to illustrate reading from FileReader // using Scanner Class reading entire File // without using loop import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ReadingEntireFileWithoutLoop { public static void main(String[] args) throws FileNotFoundException { File file = new File("C:\\Users\\pankaj\\Desktop\\test.txt"); Scanner sc = new Scanner(file); // we just need to use \\Z as delimiter sc.useDelimiter("\\Z"); System.out.println(sc.next()); } }

File Reader - using Scanner class

// Java Program to illustrate reading from Text File // using Scanner Class import java.io.File; import java.util.Scanner; public class ReadFromFileUsingScanner { public static void main(String[] args) throws Exception { // pass the path to the file as a parameter File file = new File("C:\\Users\\pankaj\\Desktop\\test.txt"); Scanner sc = new Scanner(file); while (sc.hasNextLine()) System.out.println(sc.nextLine()); } }

File Reader - reading text file as String

// Java Program to illustrate reading from text file // as string in Java package io; import java.nio.file.*;; public class ReadTextAsString { public static String readFileAsString(String fileName)throws Exception { String data = ""; data = new String(Files.readAllBytes(Paths.get(fileName))); return data; } public static void main(String[] args) throws Exception { String data = readFileAsString("C:\\Users\\pankaj\\Desktop\\test.java"); System.out.println(data); } }

File Writer - RandomAccessFile

// The following code writes an integer value with // offset given from the beginning of the file: private void writeToPosition(String filename, int data, long position) throws IOException { RandomAccessFile writer = new RandomAccessFile(filename, "rw"); writer.seek(position); writer.writeInt(data); writer.close(); } // If we want to read the int stored at specific // location, we can use the following method: private int readFromPosition(String filename, long position) throws IOException { int result = 0; RandomAccessFile reader = new RandomAccessFile(filename, "r"); reader.seek(position); result = reader.readInt(); reader.close(); return result; } //write an integer - edit it - and, finally, // read it back: public void whenWritingToSpecificPositionInFile_thenCorrect() throws IOException { int data1 = 2014; int data2 = 1500; writeToPosition(fileName, data1, 4); assertEquals(data1, readFromPosition(fileName, 4)); writeToPosition(fileName2, data2, 4); assertEquals(data2, readFromPosition(fileName, 4)); }

FileInputStream, example: 1) fileByteStream = new FileInputStream("myfile.txt"); 2) inFS = new Scanner(fileByteStream);

1) creates a file input stream and opens the file denoted by the String literal for reading. 2) creates a new Scanner object using the fileByteStream object.

Binary & Text -> BINARY files -> Opening file

An *ObjectInputStream* object is created and connected to a binary file as follows: *ObjectInputStream inStreamName = new* * ObjectInputStream(new* * FileInputStream(FileName));* The constructor for FileInputStream may throw a FileNotFoundException The constructor for ObjectInputStream may throw an IOException

File Reader - using Buffered Reader

BufferedReader in = new BufferedReader(Reader in, int size); // Java Program to illustrate reading from FileReader // using BufferedReader import java.io.; public class ReadFromFile2 { public static void main(String[] args)throws Exception { // We need to provide file path as the parameter: // double backquote is to avoid compiler interpret words // like \test as \t (ie. as a escape sequence) File file = new File("C:\\Users\\pankaj\\Desktop\\test.txt"); BufferedReader br = new BufferedReader(new FileReader(file)); String st; while ((st = br.readLine()) != null) System.out.println(st); } }

PrintWriter - Declare and initialize a PrintWriter variable named outSS that creates an output string stream using the underlying stream given by: StringWriter simpleStream = new StringWriter();.

PrintWriter outSS = new PrintWriter(simpleStream);

Scanner / Input Stream - Declare and initialize a Scanner variable named inSS that creates an input string stream using the String variable myStrLine.

Scanner inSS = new Scanner(myStrLine);

Print formatting - What is the output from the following print statements, assuming: float myFloat = 45.1342f;

System.out.printf("%09.3f", myFloat); (answer: 00045.134 ) System.out.printf("%.3e", myFloat); (answer: 4.513e+01 ) System.out.printf("%09.2f", myFloat); (answer: 000045.13 )

System.out

System.out.println("Output stream");

Binary & Text -> BINARY files -> Reading file

The class *ObjectInputStream* is a stream class that can be used to read from a binary file. An object of this class has methods to read strings, values of primitive types, and objects from a binary file A program using ObjectInputStream needs to import several classes from package java.io: import java.io.ObjectInputStream; import java.io.FileInputStream; import java.io.IOException;

Binary & Text -> BINARY files -> Writing to file

The class *ObjectOutputStream* is a stream class that can be used to write to a binary file. An object of this class has methods to write strings, values of primitive types, and objects to a binary file if using *ObjectOutputStream* , must import several classes from java.io: import java.io.ObjectOutputStream; import java.io.FileOutStream; import java.io.IOException;

Binary & Text -> TEXT FILES -> Scanner (reading from a text file)

The class Scanner can be used for reading from the keyboard as well as reading from a text file. *Scanner StreamObject =* *new Scanner(new FileInputStream(FileName));*

RandomAccessFile class (RAF) - seek

The file pointer can be moved to a new location with the method *seek*. *public void seek (long location ) throws* *IOException*

RandomAccessFile (RAF) class - length

The length of the file can be changed with the *setLength* method In particular, the *setLength* method can be used to empty the file *public long length ( ) throws IOException* *public void setLength(long newLength) throws IOException*

Stream - System.in, System.out, and System.err

The standard streams *System.in, System.out, and System.err* are automatically available to every Java program *System.out* is used for normal screen output *System.err* is used to output error messages to the screen The System class provides three methods (setIn, setOut, and setErr) for redirecting these standard streams: *public static void setIn(InputStream inStream)* *public static void setOut(PrintStream outStream)* *public static void setErr(PrintStream outStream)*

Sequential and Random Access - Random Access

To find out how many bank accounts are in the file: public int size() throws IOException { return (int) (file.length() / RECORD_SIZE); } // RECORD_SIZE is 12 bytes: // 4 bytes for the account number and // 8 bytes for the balance To read the nth account in the file: public BankAccount read(int n) throws IOException { file.seek(n * RECORD_SIZE); int accountNumber = file.readInt(); double balance = file.readDouble(); return new BankAccount(accountNumber, balance); } To write the nth account in the file: public void write(int n, BankAccount account) throws IOException { file.seek(n * RECORD_SIZE); file.writeInt(account.getAccountNumber()); file.writeDouble(account.getBalance()); }

Sequential and Random Access - Random Access

You can open a file either for Reading only ("r") Reading and writing ("rw") * RandomAccessFile f = new;* * RandomAcessFile("bank.dat","rw"); * To move the file pointer to a specific byte: *f.seek(n); * To get the current position of the file pointer: *long n = f.getFilePointer();* To find the number of bytes in a file: *long fileLength = f.length();*

RandomAccessFile (RAF) - example

code example; It will generate a file of a size 0 to 999 bytes and it will then fill those bytes in order with numbers from 65 to 90 (randomly chosen). *import java.io.RandomAccessFile;* *import java.util.Random;* *public class Main {* *public static void main(String[] args) {* *try {* //Open our file with read/write access *RandomAccessFile raf = new* *RandomAccessFile(args[0], "rw");* //Get a new random generator *Random rdn = new Random(); * //Our file will have a maximum size of 999 bytes *int min = 0; int max = 999;* //The alphabet has 26 letters thus we want to // generate a random offset to "pick" those letters *int amin = 0; int amax = 25;* //Get the length of our file *int length = rdn.nextInt(max - min + 1) + min;* // Set the length or size of the file, note that the we // do not have to set length of the file as the write // method will "grow" the file with each // sequential write. *raf.setLength((long)length);* //Run until our file is full *for(int i=0; i < length; i++){* //Randomly get our offset * int chr = rdn.nextInt(amax - amin + 1) + amin;* //ASCII capital letters range from 65-90, so add 65 to whatever we got *chr += 65;* //Write the int to the file *raf.write(chr);* //Output our char and where we wrote it. *System.out.printf("Writing %c at %d\n", chr,* *raf.getFilePointer());* *}* //Close our filestream. *raf.close();* * }* *catch (Exception e) { * * e.printStackTrace();* *}* *}* *}*

FileInputStream - Code line: java.io.FileInputStream; Code line: import java.io.IOException

enable the use of the FileInputStream and IOException classes respectively.

FileReader (testing for end of file)

hasNextInt() method returns true if an integer is available for reading. -The Scanner class offers multiple hasNext() methods for various data types such as int, double, String, etc..

File Writer - class

import java.io.*; public class FileRead { public static void main(String args[]) throws IOException { File file = new File("Hello1.txt"); // creates the file file.createNewFile(); // creates a FileWriter Object FileWriter writer = new FileWriter(file); // Writes the content to the file writer.write("This\n is\n an\n example\n"); writer.flush(); writer.close(); // Creates a FileReader Object FileReader fr = new FileReader(file); char [] a = new char[50]; fr.read(a); // reads the content to the array for(char c : a) System.out.print(c); // prints the characters one by one fr.close(); } } *output:* This is an example

FILE class

is like a wrapper class for files names. the *File* class constructor takes a name (abstract name) as the string argument, and produces an object that represents the file with that name. - *File* object and methods of the class *File* can be used to determine information about the file and its properties *public File (String File_Name)* *public boolean exists ( )* // tests whether there is a file with the abstract path name. *public boolean canRead ( )* // tests whether the program can read from the file. Returns true if the file named by the abstract path name exists and is readable by the program. *public boolean canWrite ( )* // tests whether the program can write to the file. Returns true if writable.....

PrintWriter / Output String - Write a statement that copies the contents of an output string stream to a String variable called myStr. Assume the StringWriter and PrintWriter variables are called simpleStream and outSS respectively.

myStr = simpleStream.toString();

Print formatting - What is the output from the following print statements, assuming: int value of -713

printf("%+04d", myInt); (answer: -713 printf("%05d", myInt); (answer: -0713 printf("%+02d", myInt); (answer: -713

Print formatting - What is the output from the following print statements, assuming: String myString = "Testing"; (show all responses inside quotes " ")

printf("%4s", myString); (answer: "Testing" printf("%8s", myString); (answer: " Testing" printf("%.4s", myString); (answer: "Test" printf("%.10s", myString); (answer: "Testing"

Print formatting - What is the output from the following print statements, assuming: int value of 301

printf("Value: %7d", myInt); (answer: Value: 301 printf("%+d", myInt); (answer: +301 printf("%08d", myInt); (answer: 00000301 printf("%+08d", myInt); (answer: +0000301

File Reader - reading whole file in a list

public static List readAllLines(Path path,Charset cs)throws IOException This method recognizes the following as line terminators: \u000D followed by \u000A, CARRIAGE RETURN followed by LINE FEED \u000A, LINE FEED \u000D, CARRIAGE RETURN // Java program to illustrate reading data from file // using nio.File import java.util.*; import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.io.*; public class ReadFileIntoList { public static List<String> readFileInList(String fileName) { List<String> lines = Collections.emptyList(); try { lines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8); } catch (IOException e) { // do something e.printStackTrace(); } return lines; } public static void main(String[] args) { List l = readFileInList("C:\\Users\\pankaj\\Desktop\\test.java"); Iterator<String> itr = l.iterator(); while (itr.hasNext()) System.out.println(itr.next()); } }

File Writer - using Files class

public void givenUsingJava7_whenWritingToFile_thenCorrect() throws IOException { String str = "Hello"; Path path = Paths.get(fileName); byte[] strToBytes = str.getBytes(); Files.write(path, strToBytes); String read = Files.readAllLines(path).get(0); assertEquals(str, read); }

File Writer - printWriter

public void givenWritingStringToFile_whenUsingPrintWriter_thenCorrect() throws IOException { FileWriter fileWriter = new FileWriter(fileName); PrintWriter printWriter = new PrintWriter(fileWriter); printWriter.print("Some String"); printWriter.printf("Product name is %s and its price is %d $", "iPhone", 1000); printWriter.close(); } *Output:* Some String Product name is iPhone and its price is 1000$

File Writer - buffered writer

public void whenWriteStringUsingBufferedWritter_thenCorrect() throws IOException { String str = "Hello"; BufferedWriter writer = new BufferedWriter(new FileWriter(fileName)); writer.write(str); writer.close(); } *Output in the file:* Hello

RandomAccessFile (RAF) class - get file pointer

returns the current location of the file pointer. locations are numbered starting with 0. *public long getFilePointer ( ) throws IOException*

Binary & Text -> TEXT FILES -> Testing for end of text file with Scanner

the Scanner class provides methods such as *hasNextInt and hasNextLine* *while (inputStream.hasNextLine( ))* *{* *line = inputStream.nextLine ( );* * count++;* * outputStream.println (count + " " + line);* *}*

RandomAccessFile (RAF) class - read and write

writes the specified byte to a file..... *public void write (int b ) throws IOException* *public void write (byte [] a ) throws IOException* writes int n to the file...... (can also write: long, double, float, char, boolean, etc.) *public final void writeInt(int n) throws* *IOException* writes string s to the file..... *public final void writeUTF(String s) throws* *IOException* reads a byte of data from file & returns as an integer in range of 0 to 255 *public int read( ) throws IOException* reads a.length bytes of data from file into array. Returns number of bytes read or -1 if end of the file. *public int read(byte[] a ) throws IOException*


संबंधित स्टडी सेट्स

Exam 3 Test Bank: Mgmt. of pts. w/ musculoskeletal disorders

View Set

Lecture 6 - secuirty Operations and Aministration

View Set

Pediatric Growth and Development, Nursing Care of Children Health Promotion and Maintenance

View Set

Intro. to Humanities Final Exam: Units 3-6

View Set

US History: Spanish-American War and Yellow Journalism

View Set

Oncology-Radiology: Medical Terminology

View Set