Главная | Обратная связь | Поможем написать вашу работу!
МегаЛекции

Зачем вторая библиотека




Зачем вторая библиотека

  ввода-вывода?                (module 12)

        IO                              NIO

       Stream oriented         Buffer oriented

       Blocking IO                Non blocking IO

                                            Selectors

 

   http: //tutorials. jenkov. com/java-nio/nio-vs-io. html

Пуллинг не подходит

Они все сделали в NIO – она была оптимизирована более серьезно

Он бы склонялся

 

 

NIO писалась под отдельную ОС. Все имеют право давать собственные имена. Вывод: Имен классов не должно быть в программе, а должны быть только интерфейсы.

 

 

   Path path=Paths. get(". " );

   System. out. println(path. toAbsolutePath());

       

   Path base=Paths. get(" G: ", " Documents and Settings/Alex" );

   System. out. println(base. toAbsolutePath());

       

   path=FileSystems. getDefault(). getPath(" testdir" );

   //path=Paths. get(" testdir" );

   System. out. println(path. toAbsolutePath());

     

   Path comb=base. resolve(" 1. txt" );

   System. out. println(comb. toAbsolutePath());

 

 

• BasicFileAttributeView: This is a view of basic

• DosFileAttributeView: This view provides the standard four supported attributes on file systems that support the DOS attributes. dos.

• PosixFileAttributeView: This view extends the basic attribute view with attributes supported on file systems that support the POSIX (Portable Operating System Interface for Unix)

• FileOwnerAttributeView: This view is supported by any file system

implementation that supports the concept of a file owner.

• AclFileAttributeView: This view supports reading or updating a file’s ACL. The NFSv4 ACL model is supported.

• UserDefinedFileAttributeView: This view enables support of metadata that is user defined.

 

 

java. nio. file. attribute. *    Iterable< FileStore> stores=FileSystems. getDefault(). getFileStores();    for(FileStore fs: stores)        System. out. println(fs);            Set< String> views=FileSystems. getDefault(). supportedFileAttributeViews();    for(String s: views)        System. out. println(s);    BasicFileAttributes batr = null;    batr = Files. readAttributes(comb, BasicFileAttributes. class, LinkOption. NOFOLLOW_LINKS);    System. out. println(batr. lastAccessTime());      BasicFileAttributeView batrV=Files. getFileAttributeView(comb, BasicFileAttributeView. class, LinkOption. NOFOLLOW_LINKS);    batr = batrV. readAttributes();    System. out. println(batr. lastAccessTime());            Files. setAttribute(comb, " dos: hidden", false, LinkOption. NOFOLLOW_LINKS);    DosFileAttributes dos=Files. readAttributes(comb, DosFileAttributes. class);    System. out. println(dos. isHidden());  

 

java. nio. file. Files

       

  Files. exists(path, options);

Files. notExists(path, options);

 

  Path tempDir = Files. createTempDirectory(" abc_" );

     Files. readAllLines(path, Charset. forName(" UTF-8" ));

 

 

 

 

Обход дерева каталогов

Files. walkFileTree(base, new MyVisitor(21));

class MyVisitor implements FileVisitor< Path> { private int count=0, maxCount; public MyVisitor(int max) { maxCount=max; }     public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {    if (count> =maxCount) return FileVisitResult. TERMINATE;    else            return FileVisitResult. CONTINUE; } public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {    System. out. println(file. getFileName());    count++;    return FileVisitResult. CONTINUE; } public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {    return FileVisitResult. CONTINUE; } public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {    return FileVisitResult. CONTINUE; } }
 

 

 

Это мы сделаем завтра

Инф. об изменениях в файловой системе WatchService watch= FileSystems. getDefault(). newWatchService();     base[S3]. register(watch, StandardWatchEventKinds. ENTRY_CREATE);        //for(;; ){      WatchKey key = watch. take();      for(WatchEvent ev: key. pollEvents())             System. out. println(ev. context()); ....      watch. close(); //ну и ресурс нужно освобождать

 

 

  package app21. pkg1;   import java. io. *; //одна биб-ка ввода-вывода import java. nio. charset. Charset; import java. nio. file. Files; import java. nio. file. Path; import java. nio. file. Paths; import java. util. Date;   class Test implements Serializable { int [][]data; Date time; public Test(int [][]d){    data = d;    time = new Date(); } }   public class App211 implements Serializable { // transient int id; // при transient не показывается информация. id инициализируется нулем.   /** * @param args the command line arguments */ public static void main(String[] args) throws IOException, ClassNotFoundException {    // TODO code application logic here    String name = " ascii. txt";    String enc = " Cp1251";      Path myFile = Paths. get(name); // NIO требует упаковку    for(String s: Files. readAllLines(myFile, Charset. forName(enc))) //возвращает коллекцию строк    {        System. out. println(s);    }            }   }
run: Hello, to all. Всем привет. СБОРКА УСПЕШНО ЗАВЕРШЕНА (общее время: 0 секунд)

 

   Path tempDir = Files. createTempDirectory(" abc_" );        System. out. println(tempDir);        Runtime. getRuntime(). addShutdownHook(null);            Files. readAllLines(path, Charset. forName(" UTF-8" ));            DirectoryStream< Path> ds=Files. newDirectoryStream(base, " *. {bmp, gif}" );    for(Path p: ds)        System. out. println(p. getFileName());    ds. close();
 

 

 

 

 

 

 

Formatter fmt = new Formatter(); // Get the current time and date. Calendar cal = Calendar. getInstance(); // Display 12-hour time format. fmt. format(" Time using 12-hour clock: %tr\n", cal); // Display 24-hour time format. fmt. format(" Time using 24-hour clock: %tT\n", cal); // Display short date format. fmt. format(" Short date format: %tD\n", cal); // Display date using full names. fmt. format(" Long date format: " ); fmt. format(" %tA %1$tB %1$td, %1$tY\n", cal); // Display complete time and date information. fmt. format(" Time and date in lowercase: %tc\n", cal);  

Класс Locale предназначен для отображения определенного региона. Под регионом принято понимать не только географическое положение, но также языковую и культурную среду. Например, помимо того, что указывается страна Швейцария, можно указать также и язык - французский или немецкий.

Определено два варианта конструкторов в классе Locale:

Locale(String language, String country)

Locale(String language, String country, String variant)

Первые два параметра в обоих конструкторах определяют язык и страну, для которой определяется локаль, согласно кодировке ISO. Список поддерживаемых стран и языков можно получить и с помощью вызова статических методов Locale. getISOLanguages() Locale. getISOCountries(), соответственно. Во втором варианте конструктора указан также строковый параметр variant, в котором кодируется информация о платформе.

Пример использования:

Locale l = new Locale(" ru", " RU" );

Locale l = new Locale(" en", " US", " WINDOWS" );

Статический метод getDefault() возвращает текущую локаль, сконструированную на основе настроек операционной системы,

под управлением которой функционирует JVM.

Для наиболее часто использующихся локалей заданы константы. Например, Locale. US или Locale. GERMAN.

https: //docs. oracle. com/javase/tutorial/i18n/resbundle/concept. html

Поделиться:





Воспользуйтесь поиском по сайту:



©2015 - 2024 megalektsii.ru Все авторские права принадлежат авторам лекционных материалов. Обратная связь с нами...