Création d'un fichier et écriture dans un fichier en utilisant le flux ( Stream ) I/O
Fichier LogFile.java
Dans l'exemple ci-dessous on ouvre un fichier log si il existe sinon on le crée. Si le fichier existe on l'ouvre pour écrire dedans .
import static java.nio.file.StandardOpenOption.*;
import java.nio.file.*;
import java.io.*;
public class LogFile {
public static void main(String[] args) {
// Convert the string to a
// byte array.
String s = "Hello World! ";
byte data[] = s.getBytes();
Path p = Paths.get("./logfile.txt");
try (OutputStream out = new BufferedOutputStream(
Files.newOutputStream(p, CREATE, APPEND))) {
out.write(data, 0, data.length);
} catch (IOException x) {
System.err.println(x);
}
}
}
Détails et explications
......
.......
Fichier LogFilePermission.java
Dans le deuxième exemple ci-dessous on crée un fichier avec des permissions spécifiques relatives aux système UNIX et à tou système utilisant le l'API POSIX pour son systeme de fichier. Le code ci-dessou peremtet de créer un fichier applé "logfile.txt " ou d'aller écrire dedans si il existe; si le ficheir est créé on doit le créé ace les d'écriture/lecture pour le propiétaire et de lecture seulemen pour le groupe du système.
import static java.nio.file.StandardOpenOption.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.io.*;
import java.util.*;
public class LogFilePermissions {
public static void main(String[] args) {
// Create the set of options for appending to the file.
Set options = new HashSet();
options.add(APPEND);
options.add(CREATE);
// Create the custom permissions attribute.
Set perms =
PosixFilePermissions.fromString("rw-r-----");
FileAttribute<Set> attr =
PosixFilePermissions.asFileAttribute(perms);
// Convert the string to a ByteBuffer.
String s = "Hello World! ";
byte data[] = s.getBytes();
ByteBuffer bb = ByteBuffer.wrap(data);
Path file = Paths.get("./permissions.log");
try (SeekableByteChannel sbc =
Files.newByteChannel(file, options, attr)) {
sbc.write(bb);
} catch (IOException x) {
System.out.println("Exception thrown: " + x);
}
}
}
Détails et explications
