SlideShare a Scribd company logo
Ввод-вывод, доступ к файловой системе
Алексей Владыкин
java.io.File
// on Windows:
File javaExecutable = new File(
"C: jdk1 .8.0 _60bin java.exe");
File networkFolder = new File(
" server  share");
// on Unix:
File lsExecutable = new File("/usr/bin/ls");
Сборка пути
String sourceDirName = "src";
String mainFileName = "Main.java";
String mainFilePath = sourceDirName
+ File.separator
+ mainFileName;
File mainFile =
new File(sourceDirName , mainFileName );
Абсолютные и относительные пути
File absoluteFile = new File("/usr/bin/java");
absoluteFile.isAbsolute (); // true
absoluteFile.getAbsolutePath ();
// /usr/bin/java
File relativeFile = new File("readme.txt");
relativeFile.isAbsolute (); // false
relativeFile.getAbsolutePath ();
// /home/stepic/readme.txt
Разбор пути
File file = new File("/usr/bin/java");
String path = file.getPath (); // /usr/bin/java
String name = file.getName (); // java
String parent = file.getParent (); // /usr/bin
Канонические пути
File file = new File("./prj /../ symlink.txt");
String canonicalPath = file.getCanonicalPath ();
// "/ home/stepic/readme.txt"
Работа с файлами
File java = new File("/usr/bin/java");
java.exists (); // true
java.isFile (); // true
java.isDirectory (); // false
java.length (); // 1536
java.lastModified ();// 1231914805000
Работа с директориями
File usrbin = new File("/usr/bin");
usrbin.exists (); // true
usrbin.isFile (); // false
usrbin.isDirectory (); // true
usrbin.list (); // String []
usrbin.listFiles (); // File []
Фильтрация файлов
File [] javaSourceFiles = dir.listFiles(
f -> f.getName (). endsWith(".java"));
// java.io.FileFilter:
// boolean accept(File pathname)
// java.io.FilenameFilter:
// boolean accept(File dir , String name)
Создание файла
try {
boolean success = file.createNewFile ();
} catch (IOException e) {
// handle error
}
Создание директории
File dir = new File("a/b/c/d");
boolean success = dir.mkdir ();
boolean success2 = dir.mkdirs ();
Удаление файла или директории
boolean success = file.delete ();
Переименование/перемещение
boolean success = file.renameTo(targetFile );
java.nio.file.Path
Path path = Paths.get("prj/stepic");
File fromPath = path.toFile ();
Path fromFile = fromPath.toPath ();
Разбор пути
Path java = Paths.get("/usr/bin/java");
java.isAbsolute (); // true
java.getFileName (); // java
java.getParent (); // /usr/bin
java.getNameCount (); // 3
java.getName (1); // bin
java.resolveSibling("javap"); // /usr/bin/javap
java.startsWith("/usr"); // true
Paths.get("/usr"). relativize(java ); // bin/java
Работа с файлами
Path java = Paths.get("/usr/bin/java");
Files.exists(java ); // true
Files.isRegularFile(java ); // true
Files.size(java ); // 1536
Files.getLastModifiedTime(java)
.toMillis (); // 1231914805000
Files.copy(java ,
Paths.get("/usr/bin/java_copy"),
StandardCopyOption.REPLACE_EXISTING );
Работа с директориями
Path usrbin = Paths.get("/usr/bin");
Files.exists(usrbin ); // true
Files.isDirectory(usrbin ); // true
try (DirectoryStream <Path > dirStream =
Files.newDirectoryStream(usrbin )) {
for (Path child : dirStream) {
System.out.println(child );
}
}
Создание директории
Path dir = Paths.get("a/b/c/d");
Files.createDirectory(dir);
Files.createDirectories(dir);
Рекурсивное удаление
Path directory = Paths.get("/tmp");
Files. walkFileTree (directory , new SimpleFileVisitor <Path >() {
@Override
public FileVisitResult visitFile(
Path file , BasicFileAttributes attrs)
throws IOException {
Files.delete(file );
return FileVisitResult .CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory (
Path dir , IOException exc) throws IOException {
if (exc == null) {
Files.delete(dir);
return FileVisitResult .CONTINUE;
} else {
throw exc;
}
}
});
Виртуальные файловые системы
Path zipPath = Paths.get("jdk1 .8.0 _60/src.zip");
try (FileSystem zipfs = FileSystems . newFileSystem (zipPath , null ))
for (Path path : zipfs. getRootDirectories ()) {
Files. walkFileTree (path , new SimpleFileVisitor <Path >() {
@Override
public FileVisitResult visitFile(
Path file , BasicFileAttributes attrs)
throws IOException {
System.out.println(file );
return FileVisitResult .CONTINUE;
}
});
}
}
Потоки байт
Ввод данных
java.io.InputStream
Вывод данных
java.io.OutputStream
package java.io;
public abstract class InputStream implements Closeable {
public abstract int read () throws IOException ;
public int read(byte b[]) throws IOException {
return read(b, 0, b.length );
}
public int read(byte b[], int off , int len)
throws IOException {
// ...
}
public long skip(long n) throws IOException {
// ...
}
public void close () throws IOException {}
// ...
}
package java.io;
public abstract class OutputStream
implements Closeable , Flushable {
public abstract void write(int b) throws IOException ;
public void write(byte b[]) throws IOException {
write(b, 0, b.length );
}
public void write(byte b[], int off , int len)
throws IOException {
// ...
}
public void flush () throws IOException {
// ...
}
public void close () throws IOException {
// ...
}
}
Копирование InputStream -> OutputStream
int totalBytesWritten = 0;
byte [] buf = new byte [1024];
int blockSize;
while (( blockSize = inputStream.read(buf)) > 0) {
outputStream.write(buf , 0, blockSize );
totalBytesWritten += blockSize;
}
InputStream inputStream =
new FileInputStream(new File("in.txt"));
OutputStream outputStream =
new FileOutputStream(new File("out.txt"));
InputStream inputStream =
Files.newInputStream(Paths.get("in.txt"));
OutputStream outputStream =
Files.newOutputStream(Paths.get("out.txt"));
try (InputStream inputStream =
Main.class. getResourceAsStream ("Main.class")) {
int read = inputStream.read ();
while (read >= 0) {
System.out.printf("%02x", read );
read = inputStream .read ();
}
}
try (Socket socket = new Socket("ya.ru", 80)) {
OutputStream outputStream = socket. getOutputStream ();
outputStream .write("GET / HTTP /1.0rnrn".getBytes ());
outputStream .flush ();
InputStream inputStream = socket. getInputStream ();
int read = inputStream.read ();
while (read >= 0) {
System.out.print (( char) read );
read = inputStream .read ();
}
}
byte [] data = {1, 2, 3, 4, 5};
InputStream inputStream =
new ByteArrayInputStream(data );
ByteArrayOutputStream outputStream =
new ByteArrayOutputStream ();
// ...
byte [] result = outputStream.toByteArray ();
package java.io;
public class DataOutputStream
extends FilterOutputStream implements DataOutput {
public DataOutputStream ( OutputStream out) {
// ...
}
public final void writeInt(int v) throws IOException {
out.write ((v >>> 24) & 0xFF);
out.write ((v >>> 16) & 0xFF);
out.write ((v >>> 8) & 0xFF);
out.write ((v >>> 0) & 0xFF);
incCount (4);
}
// ...
}
package java.io;
public class DataInputStream
extends FilterInputStream implements DataInput {
public DataInputStream (InputStream in) {
// ...
}
public final int readInt () throws IOException {
int ch1 = in.read ();
int ch2 = in.read ();
int ch3 = in.read ();
int ch4 = in.read ();
if ((ch1 | ch2 | ch3 | ch4) < 0)
throw new EOFException ();
return (( ch1 << 24) + (ch2 << 16)
+ (ch3 << 8) + (ch4 << 0));
}
// ...
}
byte [] originalData = {1, 2, 3, 4, 5};
ByteArrayOutputStream os = new ByteArrayOutputStream ();
try ( OutputStream dos = new DeflaterOutputStream (os)) {
dos.write( originalData );
}
byte [] deflatedData = os. toByteArray ();
try ( InflaterInputStream iis = new InflaterInputStream (
new ByteArrayInputStream ( deflatedData ))) {
int read = iis.read ();
while (read >= 0) {
System.out.printf("%02x", read );
read = iis.read ();
}
}
Потоки символов
Ввод данных
java.io.Reader
Вывод данных
java.io.Writer
package java.io;
public abstract class Reader implements Readable , Closeable {
public int read () throws IOException {
// ...
}
public int read(char cbuf []) throws IOException {
return read(cbuf , 0, cbuf.length );
}
public abstract int read(char cbuf[], int off , int len)
throws IOException ;
public long skip(long n) throws IOException {
// ...
}
public abstract void close () throws IOException;
// ...
}
package java.io;
public abstract class Writer
implements Appendable , Closeable , Flushable {
public void write(int c) throws IOException {
// ...
}
public void write(char cbuf []) throws IOException {
write(cbuf , 0, cbuf.length );
}
public abstract void write(char cbuf[], int off , int len)
throws IOException ;
public abstract void flush () throws IOException;
public abstract void close () throws IOException;
// ...
}
Reader reader =
new InputStreamReader(inputStream , "UTF -8");
Charset charset = StandardCharsets.UTF_8;
Writer writer =
new OutputStreamWriter(outputStream , charset );
Reader reader = new FileReader("in.txt");
Writer writer = new FileWriter("out.txt");
Reader reader2 = new InputStreamReader (
new FileInputStream ("in.txt"), StandardCharsets .UTF_8 );
Writer writer2 = new OutputStreamWriter (
new FileOutputStream ("out.txt"), StandardCharsets .UTF_8 );
Reader reader = new CharArrayReader (
new char [] {’a’, ’b’, ’c’});
Reader reader2 = new StringReader ("Hello World!");
CharArrayWriter writer = new CharArrayWriter ();
writer.write("Test");
char [] resultArray = writer. toCharArray ();
StringWriter writer2 = new StringWriter ();
writer2.write("Test");
String resultString = writer2.toString ();
package java.io;
public class BufferedReader extends Reader {
public BufferedReader (Reader in) {
// ...
}
public String readLine () throws IOException {
// ...
}
// ...
}
try ( BufferedReader reader =
new BufferedReader (
new InputStreamReader (
new FileInputStream ("in.txt"),
StandardCharsets .UTF_8 ))) {
String line;
while (( line = reader.readLine ()) != null) {
// process line
}
}
try ( BufferedReader reader = Files. newBufferedReader (
Paths.get("in.txt"), StandardCharsets .UTF_8 )) {
String line;
while (( line = reader.readLine ()) != null) {
// process line
}
}
List <String > lines = Files. readAllLines (
Paths.get("in.txt"), StandardCharsets .UTF_8 );
for (String line : lines) {
// process line
}
try ( BufferedWriter writer = Files. newBufferedWriter (
Paths.get("out.txt"), StandardCharsets .UTF_8 )) {
writer.write("Hello");
writer.newLine ();
}
List <String > lines = Arrays.asList("Hello", "world");
Files.write(Paths.get("out.txt"), lines ,
StandardCharsets .UTF_8 );
package java.io;
public class PrintWriter extends Writer {
public PrintWriter (Writer out) {
// ...
}
public void print(int i) {
// ...
}
public void println(Object obj) {
// ...
}
public PrintWriter printf(String format , Object ... args) {
// ...
}
public boolean checkError () {
// ...
}
// ...
}
package java.io;
public class PrintStream extends FilterOutputStream
implements Appendable , Closeable {
public PrintStream ( OutputStream out) {
// ...
}
public void print(int i) {
// ...
}
public void println(Object obj) {
// ...
}
public PrintWriter printf(String format , Object ... args) {
// ...
}
public boolean checkError () {
// ...
}
// ...
}
// java.io.StreamTokenizer
StreamTokenizer streamTokenizer =
new StreamTokenizer(
new StringReader("Hello world"));
// java.util.StringTokenizer
StringTokenizer stringTokenizer =
new StringTokenizer("Hello world");
Reader reader = new StringReader(
"abc|true |1,1e3|-42");
Scanner scanner = new Scanner(reader)
.useDelimiter("|")
.useLocale(Locale.forLanguageTag("ru"));
String token = scanner.next ();
boolean bool = scanner.nextBoolean ();
double dbl = scanner.nextDouble ();
int integer = scanner.nextInt ();
package java.lang;
public final class System {
public static final InputStream in = null;
public static final PrintStream out = null;
public static final PrintStream err = null;
// ...
}

More Related Content

What's hot

NIO and NIO2
NIO and NIO2NIO and NIO2
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011julien.ponge
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Camp
julien.ponge
 
Initial Java Core Concept
Initial Java Core ConceptInitial Java Core Concept
Initial Java Core Concept
Rays Technologies
 
Why Learn Python?
Why Learn Python?Why Learn Python?
Why Learn Python?
Christine Cheung
 
Java VS Python
Java VS PythonJava VS Python
Java VS Python
Simone Federici
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical FileSoumya Behera
 
Software Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW SydneySoftware Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW Sydneyjulien.ponge
 
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Uehara Junji
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
Ganesh Samarthyam
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
Ganesh Samarthyam
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)Alok Kumar
 
Easy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVEEasy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVE
Uehara Junji
 
C# features through examples
C# features through examplesC# features through examples
C# features through examples
Zayen Chagra
 
Metaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common LispMetaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common Lisp
Damien Cassou
 
ikh331-06-distributed-programming
ikh331-06-distributed-programmingikh331-06-distributed-programming
ikh331-06-distributed-programmingAnung Ariwibowo
 

What's hot (20)

Unit Testing with Foq
Unit Testing with FoqUnit Testing with Foq
Unit Testing with Foq
 
NIO and NIO2
NIO and NIO2NIO and NIO2
NIO and NIO2
 
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Camp
 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
 
Initial Java Core Concept
Initial Java Core ConceptInitial Java Core Concept
Initial Java Core Concept
 
Why Learn Python?
Why Learn Python?Why Learn Python?
Why Learn Python?
 
Java VS Python
Java VS PythonJava VS Python
Java VS Python
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
Software Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW SydneySoftware Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW Sydney
 
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)
 
Easy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVEEasy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVE
 
C# features through examples
C# features through examplesC# features through examples
C# features through examples
 
Metaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common LispMetaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common Lisp
 
ikh331-06-distributed-programming
ikh331-06-distributed-programmingikh331-06-distributed-programming
ikh331-06-distributed-programming
 
java sockets
 java sockets java sockets
java sockets
 

Viewers also liked

4.6 Особенности наследования в C++
4.6 Особенности наследования в C++4.6 Особенности наследования в C++
4.6 Особенности наследования в C++
DEVTYPE
 
4.2 Перегрузка
4.2 Перегрузка4.2 Перегрузка
4.2 Перегрузка
DEVTYPE
 
3.7 Конструктор копирования и оператор присваивания
3.7 Конструктор копирования и оператор присваивания3.7 Конструктор копирования и оператор присваивания
3.7 Конструктор копирования и оператор присваивания
DEVTYPE
 
Квадратичная математика
Квадратичная математикаКвадратичная математика
Квадратичная математика
DEVTYPE
 
2.8 Строки и ввод-вывод
2.8 Строки и ввод-вывод2.8 Строки и ввод-вывод
2.8 Строки и ввод-вывод
DEVTYPE
 
2.3 Указатели и массивы
2.3 Указатели и массивы2.3 Указатели и массивы
2.3 Указатели и массивы
DEVTYPE
 
3.4 Объекты и классы
3.4 Объекты и классы3.4 Объекты и классы
3.4 Объекты и классы
DEVTYPE
 
2.7 Многомерные массивы
2.7 Многомерные массивы2.7 Многомерные массивы
2.7 Многомерные массивы
DEVTYPE
 
3.5 Модификаторы доступа
3.5 Модификаторы доступа3.5 Модификаторы доступа
3.5 Модификаторы доступа
DEVTYPE
 
6.3 Специализация шаблонов
6.3 Специализация шаблонов6.3 Специализация шаблонов
6.3 Специализация шаблонов
DEVTYPE
 
5.4 Ключевые слова static и inline
5.4 Ключевые слова static и inline5.4 Ключевые слова static и inline
5.4 Ключевые слова static и inline
DEVTYPE
 
6.1 Шаблоны классов
6.1 Шаблоны классов6.1 Шаблоны классов
6.1 Шаблоны классов
DEVTYPE
 
2.4 Использование указателей
2.4 Использование указателей2.4 Использование указателей
2.4 Использование указателей
DEVTYPE
 
4.5 Объектно-ориентированное программирование
4.5 Объектно-ориентированное программирование4.5 Объектно-ориентированное программирование
4.5 Объектно-ориентированное программирование
DEVTYPE
 
1. Введение в Java
1. Введение в Java1. Введение в Java
1. Введение в Java
DEVTYPE
 
3.3 Конструкторы и деструкторы
3.3 Конструкторы и деструкторы3.3 Конструкторы и деструкторы
3.3 Конструкторы и деструкторы
DEVTYPE
 
2.5 Ссылки
2.5 Ссылки2.5 Ссылки
2.5 Ссылки
DEVTYPE
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. Streams
DEVTYPE
 
4.3 Виртуальные методы
4.3 Виртуальные методы4.3 Виртуальные методы
4.3 Виртуальные методы
DEVTYPE
 
6.2 Шаблоны функций
6.2 Шаблоны функций6.2 Шаблоны функций
6.2 Шаблоны функций
DEVTYPE
 

Viewers also liked (20)

4.6 Особенности наследования в C++
4.6 Особенности наследования в C++4.6 Особенности наследования в C++
4.6 Особенности наследования в C++
 
4.2 Перегрузка
4.2 Перегрузка4.2 Перегрузка
4.2 Перегрузка
 
3.7 Конструктор копирования и оператор присваивания
3.7 Конструктор копирования и оператор присваивания3.7 Конструктор копирования и оператор присваивания
3.7 Конструктор копирования и оператор присваивания
 
Квадратичная математика
Квадратичная математикаКвадратичная математика
Квадратичная математика
 
2.8 Строки и ввод-вывод
2.8 Строки и ввод-вывод2.8 Строки и ввод-вывод
2.8 Строки и ввод-вывод
 
2.3 Указатели и массивы
2.3 Указатели и массивы2.3 Указатели и массивы
2.3 Указатели и массивы
 
3.4 Объекты и классы
3.4 Объекты и классы3.4 Объекты и классы
3.4 Объекты и классы
 
2.7 Многомерные массивы
2.7 Многомерные массивы2.7 Многомерные массивы
2.7 Многомерные массивы
 
3.5 Модификаторы доступа
3.5 Модификаторы доступа3.5 Модификаторы доступа
3.5 Модификаторы доступа
 
6.3 Специализация шаблонов
6.3 Специализация шаблонов6.3 Специализация шаблонов
6.3 Специализация шаблонов
 
5.4 Ключевые слова static и inline
5.4 Ключевые слова static и inline5.4 Ключевые слова static и inline
5.4 Ключевые слова static и inline
 
6.1 Шаблоны классов
6.1 Шаблоны классов6.1 Шаблоны классов
6.1 Шаблоны классов
 
2.4 Использование указателей
2.4 Использование указателей2.4 Использование указателей
2.4 Использование указателей
 
4.5 Объектно-ориентированное программирование
4.5 Объектно-ориентированное программирование4.5 Объектно-ориентированное программирование
4.5 Объектно-ориентированное программирование
 
1. Введение в Java
1. Введение в Java1. Введение в Java
1. Введение в Java
 
3.3 Конструкторы и деструкторы
3.3 Конструкторы и деструкторы3.3 Конструкторы и деструкторы
3.3 Конструкторы и деструкторы
 
2.5 Ссылки
2.5 Ссылки2.5 Ссылки
2.5 Ссылки
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. Streams
 
4.3 Виртуальные методы
4.3 Виртуальные методы4.3 Виртуальные методы
4.3 Виртуальные методы
 
6.2 Шаблоны функций
6.2 Шаблоны функций6.2 Шаблоны функций
6.2 Шаблоны функций
 

Similar to 5. Ввод-вывод, доступ к файловой системе

Code red SUM
Code red SUMCode red SUM
Code red SUM
Shumail Haider
 
Application-Specific Models and Pointcuts using a Logic Meta Language
Application-Specific Models and Pointcuts using a Logic Meta LanguageApplication-Specific Models and Pointcuts using a Logic Meta Language
Application-Specific Models and Pointcuts using a Logic Meta Language
ESUG
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
Hamid Ghorbani
 
자바스터디 4
자바스터디 4자바스터디 4
자바스터디 4jangpd007
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streamsShahjahan Samoon
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
Rafael Winterhalter
 
Active Software Documentation using Soul and IntensiVE
Active Software Documentation using Soul and IntensiVEActive Software Documentation using Soul and IntensiVE
Active Software Documentation using Soul and IntensiVEkim.mens
 
Apache Beam de A à Z
 Apache Beam de A à Z Apache Beam de A à Z
Apache Beam de A à Z
Paris Data Engineers !
 
--import statemnts for Random- Scanner and IO import java-util-Random-.pdf
--import statemnts for Random- Scanner and IO import java-util-Random-.pdf--import statemnts for Random- Scanner and IO import java-util-Random-.pdf
--import statemnts for Random- Scanner and IO import java-util-Random-.pdf
ganisyedtrd
 
Lab4
Lab4Lab4
Java 7 - short intro to NIO.2
Java 7 - short intro to NIO.2Java 7 - short intro to NIO.2
Java 7 - short intro to NIO.2
Martijn Verburg
 
Session 23 - JDBC
Session 23 - JDBCSession 23 - JDBC
Session 23 - JDBC
PawanMM
 
JDBC
JDBCJDBC
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
cherryreddygannu
 
Files and streams In Java
Files and streams In JavaFiles and streams In Java
Files and streams In Java
Rajan Shah
 

Similar to 5. Ввод-вывод, доступ к файловой системе (20)

Code red SUM
Code red SUMCode red SUM
Code red SUM
 
Bhaloo
BhalooBhaloo
Bhaloo
 
Application-Specific Models and Pointcuts using a Logic Meta Language
Application-Specific Models and Pointcuts using a Logic Meta LanguageApplication-Specific Models and Pointcuts using a Logic Meta Language
Application-Specific Models and Pointcuts using a Logic Meta Language
 
CORE JAVA-1
CORE JAVA-1CORE JAVA-1
CORE JAVA-1
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
자바스터디 4
자바스터디 4자바스터디 4
자바스터디 4
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
 
Active Software Documentation using Soul and IntensiVE
Active Software Documentation using Soul and IntensiVEActive Software Documentation using Soul and IntensiVE
Active Software Documentation using Soul and IntensiVE
 
Apache Beam de A à Z
 Apache Beam de A à Z Apache Beam de A à Z
Apache Beam de A à Z
 
Inheritance
InheritanceInheritance
Inheritance
 
--import statemnts for Random- Scanner and IO import java-util-Random-.pdf
--import statemnts for Random- Scanner and IO import java-util-Random-.pdf--import statemnts for Random- Scanner and IO import java-util-Random-.pdf
--import statemnts for Random- Scanner and IO import java-util-Random-.pdf
 
Lab4
Lab4Lab4
Lab4
 
Jug java7
Jug java7Jug java7
Jug java7
 
Java 7 - short intro to NIO.2
Java 7 - short intro to NIO.2Java 7 - short intro to NIO.2
Java 7 - short intro to NIO.2
 
Session 23 - JDBC
Session 23 - JDBCSession 23 - JDBC
Session 23 - JDBC
 
JDBC
JDBCJDBC
JDBC
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
 
5java Io
5java Io5java Io
5java Io
 
Files and streams In Java
Files and streams In JavaFiles and streams In Java
Files and streams In Java
 

More from DEVTYPE

Рукописные лекции по линейной алгебре
Рукописные лекции по линейной алгебреРукописные лекции по линейной алгебре
Рукописные лекции по линейной алгебре
DEVTYPE
 
1.4 Точечные оценки и их свойства
1.4 Точечные оценки и их свойства1.4 Точечные оценки и их свойства
1.4 Точечные оценки и их свойства
DEVTYPE
 
1.3 Описательная статистика
1.3 Описательная статистика1.3 Описательная статистика
1.3 Описательная статистика
DEVTYPE
 
1.2 Выборка. Выборочное пространство
1.2 Выборка. Выборочное пространство1.2 Выборка. Выборочное пространство
1.2 Выборка. Выборочное пространство
DEVTYPE
 
Continuity and Uniform Continuity
Continuity and Uniform ContinuityContinuity and Uniform Continuity
Continuity and Uniform Continuity
DEVTYPE
 
Coin Change Problem
Coin Change ProblemCoin Change Problem
Coin Change Problem
DEVTYPE
 
Recurrences
RecurrencesRecurrences
Recurrences
DEVTYPE
 
D-кучи и их применение
D-кучи и их применениеD-кучи и их применение
D-кучи и их применение
DEVTYPE
 
Диаграммы Юнга, плоские разбиения и знакочередующиеся матрицы
Диаграммы Юнга, плоские разбиения и знакочередующиеся матрицыДиаграммы Юнга, плоские разбиения и знакочередующиеся матрицы
Диаграммы Юнга, плоские разбиения и знакочередующиеся матрицы
DEVTYPE
 
ЖАДНЫЕ АЛГОРИТМЫ
ЖАДНЫЕ АЛГОРИТМЫ ЖАДНЫЕ АЛГОРИТМЫ
ЖАДНЫЕ АЛГОРИТМЫ
DEVTYPE
 
Скорость роста функций
Скорость роста функцийСкорость роста функций
Скорость роста функций
DEVTYPE
 
Asymptotic Growth of Functions
Asymptotic Growth of FunctionsAsymptotic Growth of Functions
Asymptotic Growth of Functions
DEVTYPE
 
Кучи
КучиКучи
Кучи
DEVTYPE
 
Кодирование Хаффмана
Кодирование ХаффманаКодирование Хаффмана
Кодирование Хаффмана
DEVTYPE
 
Жадные алгоритмы: введение
Жадные алгоритмы: введениеЖадные алгоритмы: введение
Жадные алгоритмы: введение
DEVTYPE
 
Разбор задач по дискретной вероятности
Разбор задач по дискретной вероятностиРазбор задач по дискретной вероятности
Разбор задач по дискретной вероятности
DEVTYPE
 
Разбор задач модуля "Теория графов ll"
Разбор задач модуля "Теория графов ll"Разбор задач модуля "Теория графов ll"
Разбор задач модуля "Теория графов ll"
DEVTYPE
 
Наибольший общий делитель
Наибольший общий делительНаибольший общий делитель
Наибольший общий делитель
DEVTYPE
 
Числа Фибоначчи
Числа ФибоначчиЧисла Фибоначчи
Числа Фибоначчи
DEVTYPE
 
О-символика
О-символикаО-символика
О-символика
DEVTYPE
 

More from DEVTYPE (20)

Рукописные лекции по линейной алгебре
Рукописные лекции по линейной алгебреРукописные лекции по линейной алгебре
Рукописные лекции по линейной алгебре
 
1.4 Точечные оценки и их свойства
1.4 Точечные оценки и их свойства1.4 Точечные оценки и их свойства
1.4 Точечные оценки и их свойства
 
1.3 Описательная статистика
1.3 Описательная статистика1.3 Описательная статистика
1.3 Описательная статистика
 
1.2 Выборка. Выборочное пространство
1.2 Выборка. Выборочное пространство1.2 Выборка. Выборочное пространство
1.2 Выборка. Выборочное пространство
 
Continuity and Uniform Continuity
Continuity and Uniform ContinuityContinuity and Uniform Continuity
Continuity and Uniform Continuity
 
Coin Change Problem
Coin Change ProblemCoin Change Problem
Coin Change Problem
 
Recurrences
RecurrencesRecurrences
Recurrences
 
D-кучи и их применение
D-кучи и их применениеD-кучи и их применение
D-кучи и их применение
 
Диаграммы Юнга, плоские разбиения и знакочередующиеся матрицы
Диаграммы Юнга, плоские разбиения и знакочередующиеся матрицыДиаграммы Юнга, плоские разбиения и знакочередующиеся матрицы
Диаграммы Юнга, плоские разбиения и знакочередующиеся матрицы
 
ЖАДНЫЕ АЛГОРИТМЫ
ЖАДНЫЕ АЛГОРИТМЫ ЖАДНЫЕ АЛГОРИТМЫ
ЖАДНЫЕ АЛГОРИТМЫ
 
Скорость роста функций
Скорость роста функцийСкорость роста функций
Скорость роста функций
 
Asymptotic Growth of Functions
Asymptotic Growth of FunctionsAsymptotic Growth of Functions
Asymptotic Growth of Functions
 
Кучи
КучиКучи
Кучи
 
Кодирование Хаффмана
Кодирование ХаффманаКодирование Хаффмана
Кодирование Хаффмана
 
Жадные алгоритмы: введение
Жадные алгоритмы: введениеЖадные алгоритмы: введение
Жадные алгоритмы: введение
 
Разбор задач по дискретной вероятности
Разбор задач по дискретной вероятностиРазбор задач по дискретной вероятности
Разбор задач по дискретной вероятности
 
Разбор задач модуля "Теория графов ll"
Разбор задач модуля "Теория графов ll"Разбор задач модуля "Теория графов ll"
Разбор задач модуля "Теория графов ll"
 
Наибольший общий делитель
Наибольший общий делительНаибольший общий делитель
Наибольший общий делитель
 
Числа Фибоначчи
Числа ФибоначчиЧисла Фибоначчи
Числа Фибоначчи
 
О-символика
О-символикаО-символика
О-символика
 

Recently uploaded

Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
e20449
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Jay Das
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 

Recently uploaded (20)

Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 

5. Ввод-вывод, доступ к файловой системе

  • 1. Ввод-вывод, доступ к файловой системе Алексей Владыкин
  • 2. java.io.File // on Windows: File javaExecutable = new File( "C: jdk1 .8.0 _60bin java.exe"); File networkFolder = new File( " server share"); // on Unix: File lsExecutable = new File("/usr/bin/ls");
  • 3. Сборка пути String sourceDirName = "src"; String mainFileName = "Main.java"; String mainFilePath = sourceDirName + File.separator + mainFileName; File mainFile = new File(sourceDirName , mainFileName );
  • 4. Абсолютные и относительные пути File absoluteFile = new File("/usr/bin/java"); absoluteFile.isAbsolute (); // true absoluteFile.getAbsolutePath (); // /usr/bin/java File relativeFile = new File("readme.txt"); relativeFile.isAbsolute (); // false relativeFile.getAbsolutePath (); // /home/stepic/readme.txt
  • 5. Разбор пути File file = new File("/usr/bin/java"); String path = file.getPath (); // /usr/bin/java String name = file.getName (); // java String parent = file.getParent (); // /usr/bin
  • 6. Канонические пути File file = new File("./prj /../ symlink.txt"); String canonicalPath = file.getCanonicalPath (); // "/ home/stepic/readme.txt"
  • 7. Работа с файлами File java = new File("/usr/bin/java"); java.exists (); // true java.isFile (); // true java.isDirectory (); // false java.length (); // 1536 java.lastModified ();// 1231914805000
  • 8. Работа с директориями File usrbin = new File("/usr/bin"); usrbin.exists (); // true usrbin.isFile (); // false usrbin.isDirectory (); // true usrbin.list (); // String [] usrbin.listFiles (); // File []
  • 9. Фильтрация файлов File [] javaSourceFiles = dir.listFiles( f -> f.getName (). endsWith(".java")); // java.io.FileFilter: // boolean accept(File pathname) // java.io.FilenameFilter: // boolean accept(File dir , String name)
  • 10. Создание файла try { boolean success = file.createNewFile (); } catch (IOException e) { // handle error }
  • 11. Создание директории File dir = new File("a/b/c/d"); boolean success = dir.mkdir (); boolean success2 = dir.mkdirs ();
  • 12. Удаление файла или директории boolean success = file.delete ();
  • 14. java.nio.file.Path Path path = Paths.get("prj/stepic"); File fromPath = path.toFile (); Path fromFile = fromPath.toPath ();
  • 15. Разбор пути Path java = Paths.get("/usr/bin/java"); java.isAbsolute (); // true java.getFileName (); // java java.getParent (); // /usr/bin java.getNameCount (); // 3 java.getName (1); // bin java.resolveSibling("javap"); // /usr/bin/javap java.startsWith("/usr"); // true Paths.get("/usr"). relativize(java ); // bin/java
  • 16. Работа с файлами Path java = Paths.get("/usr/bin/java"); Files.exists(java ); // true Files.isRegularFile(java ); // true Files.size(java ); // 1536 Files.getLastModifiedTime(java) .toMillis (); // 1231914805000 Files.copy(java , Paths.get("/usr/bin/java_copy"), StandardCopyOption.REPLACE_EXISTING );
  • 17. Работа с директориями Path usrbin = Paths.get("/usr/bin"); Files.exists(usrbin ); // true Files.isDirectory(usrbin ); // true try (DirectoryStream <Path > dirStream = Files.newDirectoryStream(usrbin )) { for (Path child : dirStream) { System.out.println(child ); } }
  • 18. Создание директории Path dir = Paths.get("a/b/c/d"); Files.createDirectory(dir); Files.createDirectories(dir);
  • 19. Рекурсивное удаление Path directory = Paths.get("/tmp"); Files. walkFileTree (directory , new SimpleFileVisitor <Path >() { @Override public FileVisitResult visitFile( Path file , BasicFileAttributes attrs) throws IOException { Files.delete(file ); return FileVisitResult .CONTINUE; } @Override public FileVisitResult postVisitDirectory ( Path dir , IOException exc) throws IOException { if (exc == null) { Files.delete(dir); return FileVisitResult .CONTINUE; } else { throw exc; } } });
  • 20. Виртуальные файловые системы Path zipPath = Paths.get("jdk1 .8.0 _60/src.zip"); try (FileSystem zipfs = FileSystems . newFileSystem (zipPath , null )) for (Path path : zipfs. getRootDirectories ()) { Files. walkFileTree (path , new SimpleFileVisitor <Path >() { @Override public FileVisitResult visitFile( Path file , BasicFileAttributes attrs) throws IOException { System.out.println(file ); return FileVisitResult .CONTINUE; } }); } }
  • 22. package java.io; public abstract class InputStream implements Closeable { public abstract int read () throws IOException ; public int read(byte b[]) throws IOException { return read(b, 0, b.length ); } public int read(byte b[], int off , int len) throws IOException { // ... } public long skip(long n) throws IOException { // ... } public void close () throws IOException {} // ... }
  • 23. package java.io; public abstract class OutputStream implements Closeable , Flushable { public abstract void write(int b) throws IOException ; public void write(byte b[]) throws IOException { write(b, 0, b.length ); } public void write(byte b[], int off , int len) throws IOException { // ... } public void flush () throws IOException { // ... } public void close () throws IOException { // ... } }
  • 24. Копирование InputStream -> OutputStream int totalBytesWritten = 0; byte [] buf = new byte [1024]; int blockSize; while (( blockSize = inputStream.read(buf)) > 0) { outputStream.write(buf , 0, blockSize ); totalBytesWritten += blockSize; }
  • 25. InputStream inputStream = new FileInputStream(new File("in.txt")); OutputStream outputStream = new FileOutputStream(new File("out.txt"));
  • 26. InputStream inputStream = Files.newInputStream(Paths.get("in.txt")); OutputStream outputStream = Files.newOutputStream(Paths.get("out.txt"));
  • 27. try (InputStream inputStream = Main.class. getResourceAsStream ("Main.class")) { int read = inputStream.read (); while (read >= 0) { System.out.printf("%02x", read ); read = inputStream .read (); } }
  • 28. try (Socket socket = new Socket("ya.ru", 80)) { OutputStream outputStream = socket. getOutputStream (); outputStream .write("GET / HTTP /1.0rnrn".getBytes ()); outputStream .flush (); InputStream inputStream = socket. getInputStream (); int read = inputStream.read (); while (read >= 0) { System.out.print (( char) read ); read = inputStream .read (); } }
  • 29. byte [] data = {1, 2, 3, 4, 5}; InputStream inputStream = new ByteArrayInputStream(data ); ByteArrayOutputStream outputStream = new ByteArrayOutputStream (); // ... byte [] result = outputStream.toByteArray ();
  • 30. package java.io; public class DataOutputStream extends FilterOutputStream implements DataOutput { public DataOutputStream ( OutputStream out) { // ... } public final void writeInt(int v) throws IOException { out.write ((v >>> 24) & 0xFF); out.write ((v >>> 16) & 0xFF); out.write ((v >>> 8) & 0xFF); out.write ((v >>> 0) & 0xFF); incCount (4); } // ... }
  • 31. package java.io; public class DataInputStream extends FilterInputStream implements DataInput { public DataInputStream (InputStream in) { // ... } public final int readInt () throws IOException { int ch1 = in.read (); int ch2 = in.read (); int ch3 = in.read (); int ch4 = in.read (); if ((ch1 | ch2 | ch3 | ch4) < 0) throw new EOFException (); return (( ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0)); } // ... }
  • 32. byte [] originalData = {1, 2, 3, 4, 5}; ByteArrayOutputStream os = new ByteArrayOutputStream (); try ( OutputStream dos = new DeflaterOutputStream (os)) { dos.write( originalData ); } byte [] deflatedData = os. toByteArray (); try ( InflaterInputStream iis = new InflaterInputStream ( new ByteArrayInputStream ( deflatedData ))) { int read = iis.read (); while (read >= 0) { System.out.printf("%02x", read ); read = iis.read (); } }
  • 34. package java.io; public abstract class Reader implements Readable , Closeable { public int read () throws IOException { // ... } public int read(char cbuf []) throws IOException { return read(cbuf , 0, cbuf.length ); } public abstract int read(char cbuf[], int off , int len) throws IOException ; public long skip(long n) throws IOException { // ... } public abstract void close () throws IOException; // ... }
  • 35. package java.io; public abstract class Writer implements Appendable , Closeable , Flushable { public void write(int c) throws IOException { // ... } public void write(char cbuf []) throws IOException { write(cbuf , 0, cbuf.length ); } public abstract void write(char cbuf[], int off , int len) throws IOException ; public abstract void flush () throws IOException; public abstract void close () throws IOException; // ... }
  • 36. Reader reader = new InputStreamReader(inputStream , "UTF -8"); Charset charset = StandardCharsets.UTF_8; Writer writer = new OutputStreamWriter(outputStream , charset );
  • 37. Reader reader = new FileReader("in.txt"); Writer writer = new FileWriter("out.txt"); Reader reader2 = new InputStreamReader ( new FileInputStream ("in.txt"), StandardCharsets .UTF_8 ); Writer writer2 = new OutputStreamWriter ( new FileOutputStream ("out.txt"), StandardCharsets .UTF_8 );
  • 38. Reader reader = new CharArrayReader ( new char [] {’a’, ’b’, ’c’}); Reader reader2 = new StringReader ("Hello World!"); CharArrayWriter writer = new CharArrayWriter (); writer.write("Test"); char [] resultArray = writer. toCharArray (); StringWriter writer2 = new StringWriter (); writer2.write("Test"); String resultString = writer2.toString ();
  • 39. package java.io; public class BufferedReader extends Reader { public BufferedReader (Reader in) { // ... } public String readLine () throws IOException { // ... } // ... }
  • 40. try ( BufferedReader reader = new BufferedReader ( new InputStreamReader ( new FileInputStream ("in.txt"), StandardCharsets .UTF_8 ))) { String line; while (( line = reader.readLine ()) != null) { // process line } }
  • 41. try ( BufferedReader reader = Files. newBufferedReader ( Paths.get("in.txt"), StandardCharsets .UTF_8 )) { String line; while (( line = reader.readLine ()) != null) { // process line } } List <String > lines = Files. readAllLines ( Paths.get("in.txt"), StandardCharsets .UTF_8 ); for (String line : lines) { // process line }
  • 42. try ( BufferedWriter writer = Files. newBufferedWriter ( Paths.get("out.txt"), StandardCharsets .UTF_8 )) { writer.write("Hello"); writer.newLine (); } List <String > lines = Arrays.asList("Hello", "world"); Files.write(Paths.get("out.txt"), lines , StandardCharsets .UTF_8 );
  • 43. package java.io; public class PrintWriter extends Writer { public PrintWriter (Writer out) { // ... } public void print(int i) { // ... } public void println(Object obj) { // ... } public PrintWriter printf(String format , Object ... args) { // ... } public boolean checkError () { // ... } // ... }
  • 44. package java.io; public class PrintStream extends FilterOutputStream implements Appendable , Closeable { public PrintStream ( OutputStream out) { // ... } public void print(int i) { // ... } public void println(Object obj) { // ... } public PrintWriter printf(String format , Object ... args) { // ... } public boolean checkError () { // ... } // ... }
  • 45. // java.io.StreamTokenizer StreamTokenizer streamTokenizer = new StreamTokenizer( new StringReader("Hello world")); // java.util.StringTokenizer StringTokenizer stringTokenizer = new StringTokenizer("Hello world");
  • 46. Reader reader = new StringReader( "abc|true |1,1e3|-42"); Scanner scanner = new Scanner(reader) .useDelimiter("|") .useLocale(Locale.forLanguageTag("ru")); String token = scanner.next (); boolean bool = scanner.nextBoolean (); double dbl = scanner.nextDouble (); int integer = scanner.nextInt ();
  • 47. package java.lang; public final class System { public static final InputStream in = null; public static final PrintStream out = null; public static final PrintStream err = null; // ... }