name: portada class: portada-slide, center, middle # Fitxers - IO .footnote[Joan Puigcerver Ibáñez] --- layout: true class: regular-slide .right[.logo[]] --- # Fitxer -> String #### Javadoc Files ``` public static String readString(Path path) throws IOException ``` #### Exemple ``` String s = Files.readString(path); System.out.println("s = " + s); ``` --- # String -> Fitxer #### Javadoc Files ``` static Path writeString(Path path, CharSequence csq, OpenOption... options) ``` #### Exemple ``` Path path = Files.createTempFile("some", ".txt"); Files.writeString(path, "this is my string"); Path anotherUtf8File = Files.createTempFile("some", ".txt"); Files.writeString(anotherUtf8File, "this is my string2", StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE); ``` --- # OpenOptions - [StandardOpenOption](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/StandardOpenOption.html) - [LinkOption](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/LinkOption.html) --- # Fitxer -> Scanner ``` Scanner scanner = new Scanner(path); while(scanner.hasNext()){ String word = scanner.next(); System.out.println(word); } ``` --- # PrintStream Escriure en un fitxer ``` Path path = Paths.get("somefile.txt"); try (OutputStream outputStream = Files.newOutputStream(path, StandardOpenOption.APPEND, StandardOpenOption.CREATE)) { PrintStream printStream = new PrintStream(outputStream, true); printStream.println("HELLO!"); } ``` ??? ``` public class Book implements Serializable { //... } ``` ?--- # classe -> fitxer ``` FileOutputStream fileOutputStream = new FileOutputStream(FILE_PATH); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); objectOutputStream.writeObject(objectToStore); objectOutputStream.flush(); objectOutputStream.close(); ``` ?--- # fitxer -> classe ``` FileInputStream fileInputStream = new FileInputStream(FILE_PATH); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); MyObjectClass storedObjecy = (MyObjectClass) objectInputStream.readObject(); objectInputStream.close(); ``` # Escriptura Streams ``` try (BufferedWriter bufferedWriter = Files.newBufferedWriter(utfFile)) { // handle reader } try (OutputStream os = Files.newOutputStream(utfFile)) { // handle outputstream } ``` # How to read strings from files ``` String s = Files.readString(utfFile);// UTF 8 System.out.println("s = " + s); ``` # Read Strig with buffer ``` try (BufferedReader bufferedReader = Files.newBufferedReader(utfFile)) { // handle reader } try (InputStream is = Files.newInputStream(utfFile)) { // handle inputstream } Biblio: https://www.marcobehler.com/guides/java-files ```