Lesson: File

1.1. Before Java 7, we can use the classic FileWriter and BufferedWriter to write text to file.

FileWriter fw = new FileWriter("test3.txt");
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Salam...");
bw.close();
fw.close();


1.2. In Java 7, there is a new NIO class named java.nio.file.Files, and we can use Files.write() to write 

both bytes and characters.

Path path = Paths.get("test.txt");
Files.write(path, "Salam, necesen?".getBytes());

List<String> list = Arrays.asList("a", "b", "c", "d");
Files.write(Path.of("test2.txt"), list);


For append mode, we can define both StandardOpenOption.CREATE and StandardOpenOption.APPEND.

iles.write(Path.of("test.txt"), "Hello...\n".getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND);


In Java 7, we need to convert the String into a byte[] before passing it to Files.write.

In Java 11, we can use the new API named Files.writeString to write a String or text directly to a file.

Files.writeString(Path.of("test.txt"), "Hello");


In Java 8, we can use the Files.newBufferedWriter to directly create a BufferedWriter object.

BufferedWriter bw = Files.newBufferedWriter(Path.of("test.txt"));
bw.write("Hello!");
bw.newLine();
bw.flush();


In Java, we use FileOutputStream to write raw bytes to a file, like an image.

Burada adinin OutputStream olmasi bizi cawdirmasin. Bunu bele yadda saxlamaq olar, Out -> col demekdir, yeni colden iceriye melumat yaziriq.

FileOutputStream fos = new FileOutputStream("test.txt");
fos.write("Parvin".getBytes());


2. How to read a file in Java

2.1. Files.lines

Stream<String> lines = Files.lines(Paths.get("test.txt"));
lines.forEach(System.out::println);


For reading in a small text file, we can use collect convert the Stream into a List<String> easily.

Stream<String> lines = Files.lines(Paths.get("test.txt"));
List<String> collect = lines.collect(Collectors.toList());
List<String> result = Files.lines(Paths.get("test.txt")).collect(Collectors.toList());
System.out.println(collect);
System.out.println(result);


This Files.readString() read a file into a string, and if the reading file size exceeds 2G, it will throws java.lang.OutOfMemoryError: Required array size too large.

String s = Files.readString(Paths.get("test.txt"));
System.out.println(s);


 This example uses Files.readAllBytes to read a file into a byte arrays byte[], if the reading file size exceeds 2G, it will throws java.lang.OutOfMemoryError: Required array size too large.

byte[] bytes = Files.readAllBytes(Paths.get("C:\\Users\\User\\Desktop\\Parvin.jpg"));
String content = new String(bytes);
System.out.println(content);

// Files.write(Path.of("C:\\Users\\User\\Desktop\\alfa.jpg"), bytes);


This example uses Files.readAllLines to read a file into a List<String>, if the file size is larger than the running JVM heap size, it will throw java.lang.OutOfMemoryError: Java heap space.

List<String> lines = Files.readAllLines(Path.of("test.txt"));
System.out.println(lines);


2.2. BufferedReader

A classic and old friend, BufferedReader example, works well in reading small and large files, and the default buffer size (8k) is large enough for most purposes.

BufferedReader br = new BufferedReader(new FileReader("test.txt"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}

In Java 8, we can use the new Files.newBufferedReader to create a BufferedReader.

String filename = "test.txt";
BufferedReader br = Files.newBufferedReader(Paths.get("test.txt"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}


In the Scanner class, the delimiter feature is still useful for reading and filtering a small file. Java 9 and Java 10 added new methods like findAll and constructors to improve the Scanner class. However, for reading in a large file, this Scanner class is slow compared to BufferedReader.

String filename = "test.txt";
Scanner sc = new Scanner(new FileReader(filename));
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}


3. How to append text to a file

In Java, for NIO APIs like Files.write, we can use StandardOpenOption.APPEND to enable the append mode. For examples:

String filename = "test.txt";
Files.write(Path.of(filename), "Salam".getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND);


Before Java 7, we can use the FileWriter to append text to a file and close the resources manually.

String content = "Hello " + new Random().nextInt();
String filename = "test.txt";
FileWriter fw = new FileWriter(filename, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
fw.close();


4. File delete

The Files.delete(Path) deletes a file, returns nothing, or throws an exception if it fails.

String filename = "test.txt";
Files.delete(Paths.get(filename));


5. Serialization and Deserialization

package org.file;

import java.io.Serializable;

public class Person implements Serializable {
private String name;
private Integer age;

public Person(String name, Integer age) {
this.name = name;
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
package org.file;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {
public static void main(String[] args) throws Exception {
String content = "Hello " + new Random().nextInt();
String filename = "test.txt";
Person person = new Person("Parvin", 31);
byte[] bytes = convertObjectToBytes(person);
Person p = (Person) convertBytesToObject(bytes);
System.out.println(p);
}

public static byte[] convertObjectToBytes(Object obj) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(obj);
return baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
throw new RuntimeException();
}

public static Object convertBytesToObject(byte[] bytes) {
InputStream is = new ByteArrayInputStream(bytes);
try (ObjectInputStream ois = new ObjectInputStream(is)) {
return ois.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
throw new RuntimeException();
}
}


***********************************************************************************                                                            Simple messaging application

-- Server side:

System.out.println("Welcome to app...");
ServerSocket serverSocket = new ServerSocket(911);
Socket socket = serverSocket.accept();

PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

boolean flag = true;
Scanner scanner = new Scanner(System.in);
while (flag) {
String message = in.readLine();
System.out.println("Client: " + message);
String response = scanner.nextLine();
out.println(response);
}

-- Client side:

Socket socket = new Socket("localhost", 911);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

boolean flag = true;
Scanner scanner = new Scanner(System.in);
while (flag) {
String response = scanner.nextLine();
out.println(response);
String serverMessage = in.readLine();
System.out.println("Server: " + serverMessage);
}


***********************************************************************************

***********************************************************************************


package org.example;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class Main {
private static ServerSocket serverSocket = null;
private static Socket socket = null;
private static PrintWriter out = null;
private static BufferedReader in = null;
private static FileWriter fw = null;
private static BufferedWriter bw = null;

public static void main(String[] args) throws Exception {
System.out.println("Welcome to app...");
System.out.println("Please press \"start\" for starting a chat and \"stop\" for ending");
Scanner in = new Scanner(System.in);
String process = in.nextLine();
if ("start".equals(process)) {
start();
} else {
System.exit(0);
}
}

public static void start() throws Exception {
System.out.println("Start chatting...");
serverSocket = new ServerSocket(911);
socket = serverSocket.accept();
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
fw = new FileWriter("test.txt", true);
bw = new BufferedWriter(fw);

boolean flag = true;
Scanner scanner = new Scanner(System.in);
while (flag) {
String message = in.readLine();
System.out.println("Client: " + message);
bw.write(message + "\n");
bw.flush();
String response = scanner.nextLine();
if ("stop".equals(response)) {
in.close();
out.close();
socket.close();
serverSocket.close();
flag = false;
}
out.println(response);
}
}
}


package org.example;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.util.Scanner;

public class Main {
private static Socket socket = null;
private static PrintWriter out = null;
private static BufferedReader in = null;
private static FileWriter fw = null;
private static BufferedWriter bw = null;

public static void main(String[] args) throws Exception {
System.out.println("Welcome to app...");
System.out.println("Please press \"start\" for starting a chat and \"stop\" for ending");
Scanner in = new Scanner(System.in);
String process = in.nextLine();
if ("start".equals(process)) {
start();
} else {
System.exit(0);
}
}

public static void start() throws Exception {
System.out.println("Start chatting...");
Socket socket = new Socket("localhost", 911);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
fw = new FileWriter("test.txt", true);
bw = new BufferedWriter(fw);
boolean flag = true;
Scanner scanner = new Scanner(System.in);
while (flag) {
String response = scanner.nextLine();
if ("stop".equals(response)) {
in.close();
out.close();
socket.close();
flag = false;
}
out.println(response);
bw.write(response + "\n");
bw.flush();
String serverMessage = in.readLine();
System.out.println("Server: " + serverMessage);
}
}
}


***********************************************************************************













1. How to create a file in Java

package az.etibarli.test7;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {
public static void main(String[] args) throws Exception {
String fileName = "/home/parvin/Desktop/File/file.txt";
String text = "Hello, World!!!";
File file = new File(fileName);

if (file.createNewFile()) {
System.out.println("File is created!");
} else {
System.out.println("File is already exists.");
}

// Write to file
try (FileWriter writer = new FileWriter(file)){
writer.write(text);
}
}
}



package az.etibarli.test7;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {
public static void main(String[] args) throws Exception {
String fileName = "/home/parvin/Desktop/File/file.txt";
String text = "Hello, World!!!";
writeToFile(fileName, text, true);
}

public static void writeToFile(String fileName, String text, boolean append) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileName, append))){
bw.write(text);
} catch (IOException e) {
e.printStackTrace();
}
}

} 


-----------------------------------------------------------------------------------------------------------------------------

*** How to write List into file and add into List from files

List<String> list = new ArrayList<>();
list.add("Parvin");
list.add("Narmin");
list.add("Pervane");

FileOutputStream fos = new FileOutputStream("test.txt");

for(int i = 0; i < list.size(); i++) {
fos.write(list.get(i).getBytes());
fos.write("\n".getBytes());
}
fos.close();

FileInputStream fis = new FileInputStream("test.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);

String line = br.readLine();
List<String> result = new ArrayList<>();
while (line != null) {
if(line != null) {
result.add(line);
}
line = br.readLine();
}

System.out.println(result);

-----------------------------------------------------------------------------------------------------------------------------

*** How to write HashMap to file and read it

Map<Integer, String> map = new HashMap<>();
map.put(1, "Parvin");
map.put(2, "Narmin");
map.put(3, "Pervane");

FileOutputStream fos = new FileOutputStream("test.txt");

for(Map.Entry<Integer, String> entry : map.entrySet()) {
fos.write(entry.getKey().toString().getBytes());
fos.write(" ".getBytes());
fos.write(entry.getValue().getBytes());
fos.write("\n".getBytes());
}
fos.close();

FileInputStream fis = new FileInputStream("test.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);

String line = br.readLine();
Map<Integer, String> result = new HashMap<>();
while (line != null) {
if(line != null) {
String[] s = line.split(" ");
result.put(Integer.valueOf(s[0]), s[1]);
}
line = br.readLine();
}

System.out.println(result);


---


Map<Integer, Author> map = new HashMap<>();
map.put(1, new Author("Parvin", "Etibarli"));
map.put(2, new Author("Narmin", "Etibarli"));

FileOutputStream fos = new FileOutputStream("test.txt");

for(Map.Entry<Integer, Author> entry : map.entrySet()) {
fos.write(entry.getKey().toString().getBytes());
fos.write(" ".getBytes());
fos.write(entry.getValue().name.getBytes());
fos.write(" ".getBytes());
fos.write(entry.getValue().surname.getBytes());
fos.write("\n".getBytes());
}
fos.close();

FileInputStream fis = new FileInputStream("test.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);

String line = br.readLine();
Map<Integer, Author> result = new HashMap<>();
while (line != null) {
if(line != null) {
String[] s = line.split(" ");
Author author = new Author(s[1], s[2]);
result.put(Integer.valueOf(s[0]), author);
}
line = br.readLine();
}

System.out.println(result);










Комментарии

Популярные сообщения из этого блога

Lesson1: JDK, JVM, JRE

SE_21_Lesson_11: Inheritance, Polymorphism

SE_21_Lesson_9: Initialization Blocks, Wrapper types, String class