file dan directory - informatika.unsyiah.ac.idinformatika.unsyiah.ac.id/~viska/pjl/p6-1 file dan...

41
File dan Directory Prepared by Viska Mutiawani 1 [email protected]

Upload: doancong

Post on 27-Mar-2019

244 views

Category:

Documents


0 download

TRANSCRIPT

File dan Directory

Prepared by Viska Mutiawani

1 [email protected]

Subtopik File dan Directory

File pada java.io

Java nio

Path

Files

2 [email protected]

File pada java.io

3 [email protected]

Class File

Class File ada di bawah package java.io

Merupakan representasi abstrak terhadap file dan directory pathname.

Ada 4 constructor pada class File, 2 diantaranya:

File file1 = new File(“data.txt”);

File file2 = new File(“C:\java”);

Dan ada banyak method yang bisa dilihat di Java API

4 [email protected]

Input/output (I/O)

import java.io.*;

Cipta objek File dan anda dapat mendapatkan infor

mengenai file tersebut.

(Bukan bermakna mencipta file baru pada harddisk)

File f = new File("example.txt");if (f.exists() && f.length() > 1000) {

f.delete();} Method name Description

canRead() returns whether file is able to be read

delete() removes file from disk

exists() whether this file exists on disk

getName() returns file's name

length() returns number of bytes in file

renameTo(file) changes name of file5 [email protected]

Membaca file

Cara mudah membaca File , anda dapat mengirimkan objek File ke Scanner. Scanner name = new Scanner(new File("file name"));

Example:File file = new File("mydata.txt");

Scanner input = new Scanner(file);

or (shorter):

Scanner input = new Scanner(new File("mydata.txt"));

6 [email protected]

File paths

absolute path: path hingga ke folder paling atas "/"

C:/Documents/smith/hw6/input/data.csv

Windows can also use backslashes to separate folders.

relative path: path tergantung dari current directorynames.datinput/kinglear.txt

Scanner input = new Scanner(new File("data/readme.txt"));

If our program is in H:/hw6 ,Scanner will look for H:/hw6/data/readme.txt

7 [email protected]

Compiler error w/ filesimport java.io.*; // for Fileimport java.util.*; // for Scanner

public class ReadFile {public static void main(String[] args) {

Scanner input = new Scanner(new File("data.txt"));

String text = input.next();System.out.println(text);

}}

The program fails to compile with the following error:

ReadFile.java:6: unreported exception java.io.FileNotFoundException;

must be caught or declared to be thrown

Scanner input = new Scanner(new File("data.txt"));

^8 [email protected]

Exceptions

exception: Objek yang mewakili error runtime. dividing an integer by 0

calling substring on a String and passing too large an index

trying to read the wrong type of value from a Scanner

trying to read a file that does not exist

Program yang ada error akan melempar/ "throws“ exception.

Kita dapat menangkap/ "catch" (handle or fix) exception.

checked exception: Error yang harus dihandle olehprogram kita (jika tidak, kompilasi tidak berhasil).

Kita harus menspesifikkan bagaimana program menghandlekegagalan proses I/O.

9 [email protected]

The throws clause

throws clause: Kata kunci pada method yang menyatakan bahwa ada unsur dalam method menghasilkan exception namun tidak ditangani.

Syntax:public static type name(params) throws type {

Example:public class ReadFile {

public static void main(String[] args)throws FileNotFoundException {

Seperti mengatakan, “Saya umumkan bahwa method ini akanmenghasilkan exception dan saya menerima konsekuensinya."

10 [email protected]

Input tokens

token: Unit dari input, dipisahkan oleh spasi. Objek Scanner membagi isi file menjadi token.

Contoh input file berikut:

23 3.14"John Smith"

Objek Scanner dapat menginterpretasi menjadi tipe data berikut:

Token Type(s)23 int, double, String3.14 double, String"John StringSmith" String

11 [email protected]

Files and input cursor

Andai ada file weather.txt yang berisi:

16.2 23.519.1 7.4 22.8

18.5 -1.8 14.9

Objek Scanner menampilkan input sebagai suatustream of characters:16.2 23.5\n19.1 7.4 22.8\n\n18.5 -1.8 14.9\n

^

input cursor: posisi sekarang pembacaan olehScanner.

12 [email protected]

Consuming tokens

consuming input: Baca input dan pindahkan cursor.

Calling nextInt etc. moves the cursor past the current token.

16.2 23.5\n19.1 7.4 22.8\n\n18.5 -1.8 14.9\n

^

double d = input.nextDouble(); // 16.2

16.2 23.5\n19.1 7.4 22.8\n\n18.5 -1.8 14.9\n

^

String s = input.next(); // "23.5"

16.2 23.5\n19.1 7.4 22.8\n\n18.5 -1.8 14.9\n

^

13 [email protected]

Scanner tests for valid input

These methods of the Scanner do not consume input;

they just give information about what the next token will be.

Useful to see what input is coming, and to avoid crashes.

These methods can be used with a console Scanner, as well.

When called on the console, they sometimes pause waiting for input.

Method Description

hasNext() returns true if there is a next token

hasNextInt() returns true if there is a next tokenand it can be read as an int

hasNextDouble() returns true if there is a next tokenand it can be read as a double

14 [email protected]

Using hasNext methods

Avoiding type mismatches:

Scanner console = new Scanner(System.in);System.out.print("How old are you? ");if (console.hasNextInt()) {

int age = console.nextInt(); // will not crash!System.out.println("Wow, " + age + " is old!");

} else {System.out.println("You didn't type an integer.");

}

Avoiding reading past the end of a file:

Scanner input = new Scanner(new File("example.txt"));if (input.hasNext()) {

String token = input.next(); // will not crash!System.out.println("next token is " + token);

}15 [email protected]

Copy fileFile f1 = new File("test1.txt");

File f2 = new File("target.txt");

InputStream in = new FileInputStream(f1);

OutputStream out = new FileOutputStream(f2);

byte[] buf = new byte[1024];

int len;

while ((len = in.read(buf)) > 0) {

out.write(buf, 0, len);

}

in.close();

out.close();

System.out.println("File berhasil dicopy!");

16 [email protected]

Java NIO

17 [email protected]

java.nio

New input/output (NIO) pertama sekali diperkenalkan pada J2SE 4.

NIO menyediakan akses cepat dan block-oriented untuk proses I/O.

Java.io vs java.nio

Stream vs block

18 [email protected]

Stream vs Block

Stream-oriented I/O

Mengurus data satu byte pada satu waktu. Suatu input stream akan menghasilkan satu byte data dan output stream akan membaca satu byte data. Walau demikian, sangatlah mudah dan sederhana dalam melakukan filter pada data stream, namun stream I/O lebih lambat.

Block-oriented I/O

Mengurus data dalam block. Setiap operasi menghasilkan dan membaca satu blok data pada satu waktu. Hasilnya proses menjadi lebih cepat, namun proses filter menjadi lebih sukar.

19 [email protected]

Sistem File Sistem file akan menyimpan

dan mengorganisasiberbagai file media sehinggamudah untuk dicapai.

Umumnya disusun menjadibentuk tree/pohon (strukturhirarki)

Pada node akar, akan adafile dan directory, kemudiandirectory tadi akanmengandung file dandirectory, kemudian directory akan mengandung file dandirectory lagi, … dst.

21 [email protected]

Apa itu path?

Setiap file dan directory pasti memiliki path/laluan pada sistem file, yang bermula dari node akar.

Contoh pada gambar sebelumnya:

/home/sally/statusReport pada Solaris OS

C:\home\sally\statusReport pada Windows

Karakter yang digunakan untuk memisahkan directory disebut delimiter. Dan bersifat spesifik terhadap OS.

Pada Solaris OS: /

Pada Windows OS: \

22 [email protected]

Class Paths dan Interface Path

Diperkenalkan pada J2SE 7 dan ada dalam package java.nio.file

Merupakan representasi dari path pada sistem file.

Objek Path mengandung nama file dan directory yang akan membentuk path sehingga dapat digunakan untuk memeriksa, melokasikan dan memanipulasi file.

Path akan mengikuti sistem file dari OS.

Objek Path dapat di-append, extract dan dibandingkan dengan path lain.

23 [email protected]

Cipta objek Path

Mencipta objek Path dengan menggunakan method get

Path p1 = Paths.get("/tmp/foo");

Path p2 = Paths.get(args[0]);

Path p3 = Paths.get(URI.create("file:///Users/joe/FileTest.java"));

Bentuk ringkas dari:

Path p4 = FileSystems.getDefault().getPath("/users/sally");

24 [email protected]

Mencapai informasi dari Path

Setiap nama directory dapat diakses dengan index.

Direktori paling atas: index 0

Direktori paling bawah: index n-1 (dimana n merupakan jumlah direktori pada Path)

25 [email protected]

Contoh penggunaan absolute Path

[email protected]

Contoh penggunaan relative path

[email protected]

Gabung dua Path

Dua path dapat digabungkan menggunakan method resolve.

[email protected]

Membandingkan dua Path

Path mensupport method equals, sehingga dua path dapat dibandingkan dengan method tersebut.

Juga memiliki method startsWith dan endsWith untuk mengecek awalan dan akhiran dari path.

[email protected]

Fitur lain dari Path

Implements Iterable sehingga bisa menggunakan method iterator untuk menjejaki unsur nama dalam path satu per satu.

Implements Comparable sehingga bisa menggunakan method compareTo, yang dapat dipakai untuk sorting

Objek Path juga dapat disimpan dalam Collection.

[email protected]

Files

[email protected]

Class Files

Class Files merupakan bagian penting dari package java.nio.file.

Class ini menyediakan static method untuk melakukan proses membaca, menulis dan memanipulasi file dan directory.

Class ini merupakan bagian dari new I/O (NIO) maka menyediakan method untuk memproses data secara block.

Sehingga operasi menjadi lebih cepat dan sederhana.

[email protected]

Baca Files

Baca seluruh isi Files

byte[] bytes = Files.readAllBytes(path);

Jika ingin diubah ke String, tinggal tambahkan:

String content = new String(bytes, charset);

Baca file terbagi menjadi per baris

List<String> lines = Files.readAllLines(path, charset);

Method-method di atas berguna untuk file teks yang tidak terlalu panjang.

[email protected]

Tulis Files

Tulis string ke Files

Files.write(path, content.getBytes(charset));

Tambah string ke Files yang telah ada isi, di bagian ujungnya

Files.write(path, content.getBytes(charset), StandardOpenOption.APPEND);

Tambah collection baris ke Files

Files.write(path, lines);

[email protected]

Baca dan Tulis Files yang lebih besar

Jika Files yang dibaca itu besar ataupun berupa binary, maka kita dapat memanfaatkan streams atau reader/writer

InputStream in = Files.newInputStream(path);OutputStream out = Files.newOutputStream(path);Reader in = Files.newBufferedReader(path, charset);Writer out = Files.newBufferedWriter(path, charset);

Method di atas mempermudah kerja kita, karena tidak perlu memakai FileInputStream, FileOutputStream, BufferedReader, or BufferedWriter.

[email protected]

Copy, pindah, hapus Files

Mengcopy satu file

Files.copy(fromPath, toPath);

Pindah satu file (maksudnya copy file dan hapus original)

Files.move(fromPath, toPath);

Dengan 2 method di atas, proses copy dan move akan gagal jika target file telah wujud. Kalau ingin mereplace file target dan copy seluruh atribut file:

Files.copy(fromPath, toPath, StandardCopyOption.REPLACE_EXISTING,

StandardCopyOption.COPY_ATTRIBUTES);

[email protected]

Copy, pindah, hapus Files

Untuk move untuk memastikan berhasil akan dihapus, namun jika tidak file original masih ada

Files.move(fromPath, toPath, StandardCopyOption.ATOMIC_MOVE);

Hapus file

Files.delete(path);

Method delete akan menghasilkan exception jika tidak wujuh, jadi cara lebih aman:

boolean deleted = Files.deleteIfExists(path);

Method delete juga dapat digunakan untuk menghapus directory.

[email protected]

Create Files dan Directories

Buat satu directory baru Files.createDirectory(path);

Dengan method di atas, semua unsur dari path haruswujud kecuali unsur directory terakhir (yang ingin dibuat)

Buat intermediate directory Files.createDirectories(path);

Buat file kosong Files.createFile(path);

Temporary file dan directory Path newPath = Files.createTempFile(dir, prefix, suffix);

Path newPath = Files.createTempFile(prefix, suffix);Path newPath = Files.createTempDirectory(dir, prefix);Path newPath = Files.createTempDirectory(prefix);

[email protected]

Mendapatkan informasi dari Files

Method berikut akan mengembalikan boolean

exists

isHidden

isReadable, isWritable, isExecutable

isRegularFile, isDirectory, isSymbolicLink

Jumlah bytes dalam file

long fileSize = Files.size(path);

getOwner yang mengembalikan UserPrincipal

readAttributes yang mengembalikan BasicFileAttributes

[email protected]

Iterating over the Files in a Directory Pada class File versi lama, proses membaca file di

directory disimpan dalam array. Namun hal ini bisamenjadi lambat jika file sangat banyak

Pada NIO, kita dapat pakai DirectoryStream yang implement iterable sehingga kita bisa pakai Iterator. try (DirectoryStream<Path> entries =

Files.newDirectoryStream(dir)){

for (Path entry : entries)Process entries

} Blok try-with-resources memastikan DirectoryStream ditutup

sesudah digunakan. Dapat memfilter dengan glob

try (DirectoryStream<Path> entries = Files.newDirectoryStream(dir, "*.java"))

[email protected]

Glob pattern

Glob pattern merupakan pola string yang dipadankan dengan string lain, seperti directory atau nama file.

[email protected]