SlideShare uma empresa Scribd logo
1 de 47
Baixar para ler offline
Ввод-вывод, доступ к файловой системе
Алексей Владыкин
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;
// ...
}

Mais conteúdo relacionado

Mais procurados

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 Campjulien.ponge
 
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 Coinsoft-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 BytecodesGanesh Samarthyam
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeGanesh 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 DevLOVEUehara Junji
 
C# features through examples
C# features through examplesC# features through examples
C# features through examplesZayen Chagra
 
Metaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common LispMetaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common LispDamien Cassou
 
ikh331-06-distributed-programming
ikh331-06-distributed-programmingikh331-06-distributed-programming
ikh331-06-distributed-programmingAnung Ariwibowo
 

Mais procurados (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
 

Destaque

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 и inlineDEVTYPE
 
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. Введение в JavaDEVTYPE
 
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. StreamsDEVTYPE
 
4.3 Виртуальные методы
4.3 Виртуальные методы4.3 Виртуальные методы
4.3 Виртуальные методыDEVTYPE
 
6.2 Шаблоны функций
6.2 Шаблоны функций6.2 Шаблоны функций
6.2 Шаблоны функцийDEVTYPE
 

Destaque (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 Шаблоны функций
 

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

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 LanguageESUG
 
자바스터디 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 JVMRafael 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
 
--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-.pdfganisyedtrd
 
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.2Martijn Verburg
 
Session 23 - JDBC
Session 23 - JDBCSession 23 - JDBC
Session 23 - JDBCPawanMM
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptxcherryreddygannu
 
Files and streams In Java
Files and streams In JavaFiles and streams In Java
Files and streams In JavaRajan Shah
 

Semelhante a 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
 

Mais de 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 ContinuityDEVTYPE
 
Coin Change Problem
Coin Change ProblemCoin Change Problem
Coin Change ProblemDEVTYPE
 
Recurrences
RecurrencesRecurrences
RecurrencesDEVTYPE
 
D-кучи и их применение
D-кучи и их применениеD-кучи и их применение
D-кучи и их применениеDEVTYPE
 
Диаграммы Юнга, плоские разбиения и знакочередующиеся матрицы
Диаграммы Юнга, плоские разбиения и знакочередующиеся матрицыДиаграммы Юнга, плоские разбиения и знакочередующиеся матрицы
Диаграммы Юнга, плоские разбиения и знакочередующиеся матрицыDEVTYPE
 
ЖАДНЫЕ АЛГОРИТМЫ
ЖАДНЫЕ АЛГОРИТМЫ ЖАДНЫЕ АЛГОРИТМЫ
ЖАДНЫЕ АЛГОРИТМЫ DEVTYPE
 
Скорость роста функций
Скорость роста функцийСкорость роста функций
Скорость роста функцийDEVTYPE
 
Asymptotic Growth of Functions
Asymptotic Growth of FunctionsAsymptotic Growth of Functions
Asymptotic Growth of FunctionsDEVTYPE
 
Кучи
КучиКучи
КучиDEVTYPE
 
Кодирование Хаффмана
Кодирование ХаффманаКодирование Хаффмана
Кодирование ХаффманаDEVTYPE
 
Жадные алгоритмы: введение
Жадные алгоритмы: введениеЖадные алгоритмы: введение
Жадные алгоритмы: введениеDEVTYPE
 
Разбор задач по дискретной вероятности
Разбор задач по дискретной вероятностиРазбор задач по дискретной вероятности
Разбор задач по дискретной вероятностиDEVTYPE
 
Разбор задач модуля "Теория графов ll"
Разбор задач модуля "Теория графов ll"Разбор задач модуля "Теория графов ll"
Разбор задач модуля "Теория графов ll"DEVTYPE
 
Наибольший общий делитель
Наибольший общий делительНаибольший общий делитель
Наибольший общий делительDEVTYPE
 
Числа Фибоначчи
Числа ФибоначчиЧисла Фибоначчи
Числа ФибоначчиDEVTYPE
 
О-символика
О-символикаО-символика
О-символикаDEVTYPE
 

Mais de 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"
 
Наибольший общий делитель
Наибольший общий делительНаибольший общий делитель
Наибольший общий делитель
 
Числа Фибоначчи
Числа ФибоначчиЧисла Фибоначчи
Числа Фибоначчи
 
О-символика
О-символикаО-символика
О-символика
 

Último

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 

Último (20)

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 

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