Skip to content

Instantly share code, notes, and snippets.

@jocile
Last active May 21, 2022 13:49
Show Gist options
  • Save jocile/fe7a8e9967983fb8df82137e9953a8a9 to your computer and use it in GitHub Desktop.
Save jocile/fe7a8e9967983fb8df82137e9953a8a9 to your computer and use it in GitHub Desktop.
Input output characters and files examples
package com.jocile.example.io;
import java.io.Serializable;
/**
* This class is used in the object serialization example.
*
* @see ObjectIoExample
*/
public class Cat implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private Integer age;
private String color;
private boolean castrated;
private transient boolean purrs; // optionally cat sound while sleeping
/**
* Construct the instance using the specified attributes
*
* @param name
* @param age
* @param color
* @param castrated
* @param purrs optional cat sound while sleeping
*/
public Cat(
String name,
Integer age,
String color,
boolean castrated,
boolean purrs
) {
this.name = name;
this.age = age;
this.color = color;
this.castrated = castrated;
this.purrs = purrs;
}
public Cat() {}
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
public String getColor() {
return color;
}
public boolean isCastrated() {
return castrated;
}
public boolean isPurrs() {
return purrs;
}
@Override
public String toString() {
return (
"Cat [age=" +
age +
", castrated=" +
castrated +
", color=" +
color +
", name=" +
name +
", purrs=" +
purrs +
"]"
);
}
}
package com.jocile.example.io;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
/**
* This is an example of character input and output manipulation.
*/
public class CharacterExample {
/**
* This method receives characters from the
* keyboard and prints to the console
* @throws IOException
*/
public static void KeyboardInAndPrint() throws IOException {
System.out.println("Enter 3 movie suggestions: ");
//Opening a data stream to receive input via the keyboard
//InputStream is = System.in;
//Bridge that transforms InputStream stream into character
//Reader isr = new InputStreamReader(is);
//reads the character stream and stores it in a buffer to make reading these characters easier
//BufferedReader br = new BufferedReader(isr);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //decorator patthern
//Preparing writing on console:
//Opening a data stream to send data to the console.
//OutputStream os = System.out;
//bridge that transforms the OutputStream stream into character
//OutputStreamWriter osr = new OutputStreamWriter(os);
//writes the character stream (text) and stores it in a buffer to facilitate writing these characters
//BufferedWriter bw = new BufferedWriter(osr);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); //decorator patthern
//Read from keyboard and send to console
//readLine method reads each line of text and returns a String.
String line = br.readLine();
do { //take the line read from the keyboard and store it in a buffer
bw.write(line);
bw.newLine(); //then insert a line
// after copying the line above, we fill the line again
line = br.readLine();
//when the line is empty, stop.
} while (!line.isEmpty());
// bw.flush(); // if closing flush is not necessary
br.close(); // Close the input stream
bw.close(); // And close the output stream
}
public static void main(String[] args) throws IOException {
KeyboardInAndPrint();
}
}
package com.jocile.example.io;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
/**
* This is an example of character input and output manipulation,
* and save to a file.
*/
public class CharacterToFileExample {
/**
* This method receives characters from the
* keyboard and saves to a file
* @throws IOException
*/
public static void KeyboardInAndPrint() throws IOException {
//Opens the stream to write to the console
PrintWriter pw = new PrintWriter(System.out);
//write to console
pw.println("Enter 3 movie suggestions: ");
pw.flush();
//read keyboard entries
Scanner scan = new Scanner(System.in);
//Saves keyboard entries to a variable
String line = scan.nextLine();
//Saves keyboard entries to a file
File f = new File("Recomendations.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(f.getName()));
do { //write to file
bw.write(line);
bw.newLine();
bw.flush();
line = scan.nextLine();
//until the end
} while (!(line.equalsIgnoreCase("end")));
//Shows a confirmation
pw.printf("The file \"%s\" was created successfully!", f.getName());
//Closing the flows
pw.close();
scan.close();
bw.close();
}
public static void main(String[] args) throws IOException {
KeyboardInAndPrint();
}
}
package com.jocile.example.io;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
/**
* This is an example of character input and output manipulation,
* and updates a file.
*/
public class CharacterToFileUpdateExample {
/**
* This method copies a file
* @throws IOException
*/
public static void fileCopy() throws IOException {
File f = new File("Recomendations.txt");
String fileName = f.getName();
// Reader r = new FileReader(fileName);
// BufferedReader br = new BufferedReader(r);
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
String fileNameCopy = fileName
.substring(0, fileName.indexOf("."))
.concat("-copy.txt");
File fcopy = new File(fileNameCopy);
BufferedWriter bw = new BufferedWriter(new FileWriter(fcopy.getName()));
do {
bw.write(line);
bw.newLine();
bw.flush();
line = br.readLine();
} while (!(line == null));
System.out.printf(
"The file \"%s\" copied successfully! With the size '%d' bytes.\n",
f.getName(),
f.length()
);
System.out.printf(
"The file \"%s\" copied successfully! With the size '%d' bytes.\n",
fcopy.getName(),
fcopy.length()
);
PrintWriter pw = new PrintWriter(System.out);
pw.println("Enter 3 new movie suggestions: and type end");
pw.flush();
fileUpdate(fcopy.getName());
pw.printf(
"File updated successfully, with the size '%d' bytes.\n",
fcopy.length()
);
br.close();
bw.close();
pw.close();
}
/**
* This method updates a file,
* adding updates at the end.
*
* @param file copy of the file name
* @throws IOException
*/
public static void fileUpdate(String file) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
BufferedWriter bw = new BufferedWriter(new FileWriter(file, true));
do {
bw.write(line);
bw.newLine();
line = br.readLine();
} while (!(line.equalsIgnoreCase("end")));
br.close();
bw.close();
}
public static void main(String[] args) throws IOException {
fileCopy();
}
}
package com.jocile.example.io;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Scanner;
/**
* This is an example of data flow using a file
*/
public class DataToFileExample {
/**
* Receiving a product's name, quantity and price and saving it to a file
*
* @throws IOException
*/
public static void addProduct() throws IOException {
//Referencing the file
File f = new File("/home/joc/Documentos/product.bin");
//Selecting output to console
PrintStream ps = new PrintStream(System.out, true); //Auto flush true
//Persisting primal types in the file
// OutputStream os = new FileOutputStream(f.getPath());
// DataOutputStream dos = new DataOutputStream(os);
DataOutputStream dos = new DataOutputStream(
new FileOutputStream(f.getPath())
); // Decorator
//Opening the stream by keyboard
Scanner scan = new Scanner(System.in);
ps.print("Product's name: ");
String name = scan.nextLine(); //Receive a string
dos.writeUTF(name); //writing in the file
ps.print("Choose your product size (P/M/G/U): ");
//Takes an integer and transforms it into a character
char size = (char) System.in.read();
dos.writeChar(size);
ps.print("Quantity: ");
int quant = scan.nextInt();
dos.writeInt(quant);
ps.print("Unit price: ");
double price = scan.nextDouble();
dos.writeDouble(price);
ps.printf( //Shows a confirmation
"The file %s has been created successfully with %d bytes \nin the directory: '%s'\n",
f.getName(),
f.length(),
f.getAbsolutePath()
);
readProduct(f.getPath()); //Read the file
dos.close(); //closing the flows
scan.close();
ps.close();
}
/**
* Receive the path and read the file
*
* @param fileName
* @throws IOException
*/
public static void readProduct(String fileName) throws IOException {
File f = new File(fileName);
// InputStream is = new FileInputStream(f.getPath());
// DataInputStream dis = new DataInputStream(is);
DataInputStream dis = new DataInputStream(new FileInputStream(f.getPath()));
//Reading the first line containing the product name
String name = dis.readUTF();
//Reading the second third line containing the character
char size = dis.readChar();
//Reading the third line that contains the integer
int quantity = dis.readInt();
//Reading the fourth line containing the double
double price = dis.readDouble();
System.out.printf("\nName..........: %s\n", name);
System.out.printf("\nSize..........: %s\n", size);
System.out.printf("\nQuantity......: %d\n", quantity);
System.out.printf("\nPrice..........: %f\n", price);
System.out.print("Total value of the product: " + (quantity * price));
dis.close();
}
public static void main(String[] args) throws IOException {
addProduct();
}
}
package com.jocile.example.io;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* This is an example of a file manipulation class.
*/
public class FileExample {
public static void main(String[] args) {
File f = new File("read-and-write-files-IO.txt");
System.out.println("Path: " + f.getName());
System.out.println("Absolute path: " + f.getAbsolutePath());
System.out.println("parent directory: " + f.getParent());
System.out.println(f.exists() ? "exists" : "not exists");
System.out.println(f.canWrite() ? "Can be saved" : "can not saved");
System.out.println(f.canRead() ? "Can be read" : "can not read");
System.out.println(f.isDirectory() ? "is directory" : "is not a directory");
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date data = new Date(f.lastModified());
System.out.println("The last modification of the file" + df.format(data));
System.out.println("File size: " + f.length() + " bytes");
}
}
package com.jocile.example.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
/**
* This class serializes an object
*/
public class ObjectIoExample {
public static void serialization() throws IOException {
Cat cat = new Cat("Simba", 6, "yellow", true, true);
File f = new File("cat");
// OutputStream os = new FileOutputStream(f.getName());
// ObjectOutputStream oos = new ObjectOutputStream(os);
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(f.getName())
);
oos.writeObject(cat);
PrintStream ps = new PrintStream(System.out);
ps.printf(
"File \"%s\" created successfully! With the size '%d' bytes\n",
f.getName(),
f.length()
);
oos.close();
ps.close();
}
public static void deserialization(String file)
throws FileNotFoundException, IOException, ClassNotFoundException {
// InputStream is = new FileInputStream(file);
// ObjjectInputStream ois = new ObjjectInputStream(is);
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
Cat objCat = (Cat) ois.readObject();
System.out.printf("\n Name ...........: %s", objCat.getName());
System.out.printf("\n Age ...........: %s", objCat.getAge());
System.out.printf("\n Color ..........: %s", objCat.getColor());
System.out.printf("\n Castratet ......: %s", objCat.isCastrated());
System.out.printf("\n Purrs ..........: %s\n", objCat.isPurrs());
System.out.println(objCat);
ois.close();
}
public static void main(String[] args)
throws IOException, ClassNotFoundException {
// serialization(); // Uncomment to serialize and comment deserialization
deserialization("cat");
}
}
Regardless of the source or destination of the data, the process of reading (input) and writing (output) data is the same:
- Reading (read)
1. Open a Stream
2. while(there is_information)
2.1 read_information
3. Close the Stream
- Writing (write)
1. Open a Stream
2. while(there is_information)
2.1 write_information
3. Close the Stream
The Spider Man
Super Man
The Revengers
The sky
Super surf
Yes you can
The Spider Man
Super Man
The Revengers
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment