Input/Output och strömmar i Java
Alex Liu
Software Developer Engineer
File-klassen kan representera antingen en fil eller en katalogmkdir() för kataloger och createNewFile() för filer)
Fileimport java.io.File;
File-objekt som representerar katalogenFile newDirectory = new File("myDirectory");
.mkdir() för att skapa den faktiska katalogen i filsystemetboolean created = newDirectory.mkdir();
true om katalogen skapas utan problemfalse om katalogen redan finns eller inte kan skapas.listFiles() för att lista filer i en katalog$$
// Creates a `File` object representing the directory `myDirectory`
File dir = new File("myDirectory");
//Retrieves an `array` of `File` objects representing the contents of `myDirectory`
File[] files = dir.listFiles();
array av File-objekt om katalogen finnsnull om katalogen inte finns// Creates a `File` object for `sample.txt` inside `myDirectory`
File file = new File("myDirectory/sample.txt");
// Retrieves the relative path of the file as a String
String path = file.getPath();
System.out.println(path);
Vi antar att myDirectory redan finns – annars misslyckas filskapande eller skrivning
Utdata:
myDirectory/sample.txt
$$
// Creates a `File` object for `sample.txt` inside `myDirectory`
File file = new File("myDirectory/sample.txt");
// Retrieves the absolute path of the file as a String
String absPath = file.getAbsolutePath();
System.out.println(absPath);
/user/home/myDirectory/sample.txt
Input/Output och strömmar i Java