Skip to content

Instantly share code, notes, and snippets.

@BacLuc
Created May 16, 2017 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BacLuc/e5774fd2c285181ba2b078f87914e28e to your computer and use it in GitHub Desktop.
Save BacLuc/e5774fd2c285181ba2b078f87914e28e to your computer and use it in GitHub Desktop.
read/write file
package com.company;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
final static String FILE_NAME = "toread.txt";
final static String OUTPUT_FILE_NAME = "toput.txt";
final static String OUTPUT_FILE_NAME2 = "toput2.txt";
final static Charset ENCODING = StandardCharsets.UTF_8;
public static void main(String[] args) {
Main main = new Main();
try {
List<String> lines =
main.readSmallTextFile(FILE_NAME);
main.writeSmallTextFile(OUTPUT_FILE_NAME,lines);
try(BufferedReader reader = Files.newBufferedReader(Paths.get(OUTPUT_FILE_NAME));
BufferedWriter writer = Files.newBufferedWriter(Paths.get(OUTPUT_FILE_NAME2), ENCODING);
){
reader.lines().forEachOrdered(s -> {
try {
writer.write(s);
writer.write("\n");
} catch (IOException e) {
e.printStackTrace();
}
});
writer.write("written by stream");
}
} catch (IOException e) {
e.printStackTrace();
}
}
List<String> readSmallTextFile(String fileName) throws IOException{
Path path = Paths.get(fileName);
return Files.readAllLines(path.toAbsolutePath(),ENCODING);
}
void writeSmallTextFile(String fileName, List<String> lines) throws IOException{
Path path = Paths.get(fileName);
lines.add("written with writeSmallTextFile");
Files.write(path.toAbsolutePath(), lines);
}
}
this is a text
this is a text
this is a text
this is a text
this is a text
this is a text
this is a text
this is a text
this is a text
this is a text
this is a text
this is a text
this is a text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment