Guest User

Untitled

a guest
Feb 21st, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. package com.myanmareffectiveprogrammer.java7.bigchanges.nio2;
  2.  
  3. import java.io.IOException;
  4. import java.nio.charset.StandardCharsets;
  5. import java.nio.file.Files;
  6. import java.nio.file.Path;
  7. import java.nio.file.Paths;
  8. import java.nio.file.StandardOpenOption;
  9. import java.util.List;
  10.  
  11. public class ReadWriteExample {
  12.  
  13. public static void main(String args[]) throws IOException {
  14. readFileAsBytes();
  15. readFileAsString();
  16. readFileAsSequencesOfLines();
  17.  
  18. writeFileAsString();
  19. writeFileAsCollectionOfLines();
  20. writeFileAsAppend();
  21. }
  22.  
  23. private static void readFileAsBytes() throws IOException {
  24. Path path = getReadFilePath();
  25.  
  26. byte[] bytes = Files.readAllBytes(path);
  27.  
  28. print(bytes);
  29. }
  30.  
  31. private static String readFileAsString() throws IOException {
  32. Path path = getReadFilePath();
  33. byte[] bytes = Files.readAllBytes(path);
  34.  
  35. String content = new String(bytes, StandardCharsets.UTF_8);
  36.  
  37. print(content);
  38. return content;
  39. }
  40.  
  41. private static List<String> readFileAsSequencesOfLines() throws IOException {
  42. Path path = getReadFilePath();
  43.  
  44. List<String> lines = Files.readAllLines(path);
  45.  
  46. print(lines);
  47. return lines;
  48. }
  49.  
  50. private static void writeFileAsString() throws IOException {
  51. String content = readFileAsString();
  52. Path path = getWriteFilePath();
  53.  
  54. Files.write(path, content.getBytes(StandardCharsets.UTF_8));
  55. }
  56.  
  57. private static void writeFileAsCollectionOfLines() throws IOException {
  58. List<String> lines = readFileAsSequencesOfLines();
  59. Path path = getWriteFilePath();
  60.  
  61. Files.write(path, lines);
  62. }
  63.  
  64. private static void writeFileAsAppend() throws IOException {
  65. List<String> lines = readFileAsSequencesOfLines();
  66. Path path = getWriteFilePath();
  67.  
  68. Files.write(path, lines, StandardOpenOption.APPEND);
  69. }
  70.  
  71. private static Path getReadFilePath() {
  72. Path path = Paths
  73. .get(".\\ReadMe.txt");
  74.  
  75. return path.normalize();
  76. }
  77.  
  78. private static Path getWriteFilePath() {
  79. Path path = Paths
  80. .get(".\\WriteMe.txt");
  81.  
  82. return path;
  83. }
  84.  
  85. private static void print(Object object) {
  86. System.out.println(object);
  87. }
  88. }
Add Comment
Please, Sign In to add comment