SlideShare ist ein Scribd-Unternehmen logo
1 von 47
Downloaden Sie, um offline zu lesen
Ввод-вывод, доступ к файловой системе
Алексей Владыкин
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;
// ...
}

Weitere ähnliche Inhalte

Was ist angesagt?

Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011
julien.ponge
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
Soumya 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 Sydney
julien.ponge
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)
Alok Kumar
 
ikh331-06-distributed-programming
ikh331-06-distributed-programmingikh331-06-distributed-programming
ikh331-06-distributed-programming
Anung Ariwibowo
 

Was ist angesagt? (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
 

Andere mochten auch

6.3 Специализация шаблонов
6.3 Специализация шаблонов6.3 Специализация шаблонов
6.3 Специализация шаблонов
DEVTYPE
 

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

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

자바스터디 4
자바스터디 4자바스터디 4
자바스터디 4
jangpd007
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
Shahjahan Samoon
 
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
kim.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-.pdf
ganisyedtrd
 

Ähnlich wie 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
 

Mehr von DEVTYPE

D-кучи и их применение
D-кучи и их применениеD-кучи и их применение
D-кучи и их применение
DEVTYPE
 

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

Kürzlich hochgeladen

+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
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 

Kürzlich hochgeladen (20)

+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...
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 

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