Ввод-вывод, доступ к файловой системе
Алексей Владыкин
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

PDF
4. Обработка ошибок, исключения, отладка
PDF
3. Объекты, классы и пакеты в Java
PDF
Apache Commons - Don\'t re-invent the wheel
PPTX
Use of Apache Commons and Utilities
PDF
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
PPTX
Lexical environment in ecma 262 5
PDF
Java 7 LavaJUG
PDF
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
4. Обработка ошибок, исключения, отладка
3. Объекты, классы и пакеты в Java
Apache Commons - Don\'t re-invent the wheel
Use of Apache Commons and Utilities
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
Lexical environment in ecma 262 5
Java 7 LavaJUG
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...

What's hot (20)

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

Viewers also liked (20)

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

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

PPTX
File Input and output.pptx
ODP
Java IO. Streams
PPTX
Understanding java streams
PDF
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
PDF
Java Day-6
PDF
Java Programming - 06 java file io
PPTX
Java Tutorial Lab 6
PDF
5java Io
PDF
26 io -ii file handling
PPTX
IO Programming.pptx all informatiyon ppt
PPTX
Input/Output Exploring java.io
PPTX
IOStream.pptx
PPTX
Input output files in java
PPTX
Java I/O
PPTX
File handling
DOC
H U F F M A N Algorithm
PDF
PDF
File. Java
PPTX
PPT
File Input and Output in Java Programing language
File Input and output.pptx
Java IO. Streams
Understanding java streams
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
Java Day-6
Java Programming - 06 java file io
Java Tutorial Lab 6
5java Io
26 io -ii file handling
IO Programming.pptx all informatiyon ppt
Input/Output Exploring java.io
IOStream.pptx
Input output files in java
Java I/O
File handling
H U F F M A N Algorithm
File. Java
File Input and Output in Java Programing language

More from DEVTYPE (20)

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

Recently uploaded (20)

PPTX
Plex Media Server 1.28.2.6151 With Crac5 2022 Free .
PDF
Understanding the Need for Systemic Change in Open Source Through Intersectio...
PPTX
DevOpsDays Halifax 2025 - Building 10x Organizations Using Modern Productivit...
PDF
Streamlining Project Management in Microsoft Project, Planner, and Teams with...
PPTX
Folder Lock 10.1.9 Crack With Serial Key
PDF
Cloud Native Aachen Meetup - Aug 21, 2025
PDF
Sanket Mhaiskar Resume - Senior Software Engineer (Backend, AI)
PPTX
ERP Manufacturing Modules & Consulting Solutions : Contetra Pvt Ltd
PDF
Website Design & Development_ Professional Web Design Services.pdf
PDF
Top 10 Project Management Software for Small Teams in 2025.pdf
PDF
Sun and Bloombase Spitfire StoreSafe End-to-end Storage Security Solution
PPTX
ROI from Efficient Content & Campaign Management in the Digital Media Industry
PPTX
Lecture 5 Software Requirement Engineering
PPTX
Bandicam Screen Recorder 8.2.1 Build 2529 Crack
PPT
3.Software Design for software engineering
PPTX
HackYourBrain__UtrechtJUG__11092025.pptx
PPTX
Foundations of Marketo Engage: Nurturing
PPTX
Viber For Windows 25.7.1 Crack + Serial Keygen
PPTX
DevOpsDays Halifax 2025 - Building 10x Organizations Using Modern Productivit...
PDF
Lumion Pro Crack New latest version Download 2025
Plex Media Server 1.28.2.6151 With Crac5 2022 Free .
Understanding the Need for Systemic Change in Open Source Through Intersectio...
DevOpsDays Halifax 2025 - Building 10x Organizations Using Modern Productivit...
Streamlining Project Management in Microsoft Project, Planner, and Teams with...
Folder Lock 10.1.9 Crack With Serial Key
Cloud Native Aachen Meetup - Aug 21, 2025
Sanket Mhaiskar Resume - Senior Software Engineer (Backend, AI)
ERP Manufacturing Modules & Consulting Solutions : Contetra Pvt Ltd
Website Design & Development_ Professional Web Design Services.pdf
Top 10 Project Management Software for Small Teams in 2025.pdf
Sun and Bloombase Spitfire StoreSafe End-to-end Storage Security Solution
ROI from Efficient Content & Campaign Management in the Digital Media Industry
Lecture 5 Software Requirement Engineering
Bandicam Screen Recorder 8.2.1 Build 2529 Crack
3.Software Design for software engineering
HackYourBrain__UtrechtJUG__11092025.pptx
Foundations of Marketo Engage: Nurturing
Viber For Windows 25.7.1 Crack + Serial Keygen
DevOpsDays Halifax 2025 - Building 10x Organizations Using Modern Productivit...
Lumion Pro Crack New latest version Download 2025

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; // ... }