Модераторы: LSD, AntonSaburov

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Файловый вывод, проблемы с кодировкой 
V
    Опции темы
Beard
Дата 29.5.2006, 18:09 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 228
Регистрация: 5.7.2005
Где: Санкт-Петербург

Репутация: 2
Всего: 9



Попробуй для проверки запустить вот это:
Код

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

public class Locking {
    public static void main(String args[]) throws IOException {
        if (args.length == 0)
            System.out.println("Use \"java Locking filename\"");
        else {
            FileChannel channel = new RandomAccessFile(args[0], "rw").getChannel();
            FileLock lock = channel.lock();//or channel.tryLock(); lock() return FileLock
            try {
                System.out.println("GOT LOCK");
                System.out.println("Now you can try edit or delete file \"" + args[0] + "\"");
                System.out.println("Press ENTER to continue");
                System.in.read(new byte[10]);
            } finally {
                System.out.println("RELEASED LOCK");
                lock.release();
                channel.close();
            }
            System.out.println("OK");
        }
    }
}

Цитата(Bulat @  29.5.2006,  14:04 Найти цитируемый пост)
Что там делается lock я не понял........ 

Вот что написано в Thinking in Java 3 Edition:
Цитата

File locking, introduced in JDK 1.4, allows you to synchronize access to a file as a shared resource. However, the two threads that contend for the same file may be in different JVMs, or one may be a Java thread and the other some native thread in the operating system. The file locks are visible to other operating system processes because Java file locking maps directly to the native operating system locking facility. 

... skipped ...

You get a FileLock on the entire file by calling either tryLock( ) or lock( ) on a FileChannel. (SocketChannel, DatagramChannel, and ServerSocketChannel do not need locking since they are inherently single-process entities; you don’t generally share a network socket between two processes.) tryLock( ) is non-blocking. It tries to grab the lock, but if it cannot (when some other process already holds the same lock and it is not shared), it simply returns from the method call. lock( ) blocks until the lock is acquired, or the thread that invoked lock( ) is interrupted, or the channel on which the lock( ) method is called is closed. A lock is released using FileLock.release( ). 

It is also possible to lock a part of the file by using

    tryLock(long position, long size, boolean shared)
or
    lock(long position, long size, boolean shared)

which locks the region (size - position). The third argument specifies whether this lock is shared. Feedback

Although the zero-argument locking methods adapt to changes in the size of a file, locks with a fixed size do not change if the file size changes. If a lock is acquired for a region from position to position+size and the file increases beyond position+size, then the section beyond position+size is not locked. The zero-argument locking methods lock the entire file, even if it grows. Feedback

Support for exclusive or shared locks must be provided by the underlying operating system. If the operating system does not support shared locks and a request is made for one, an exclusive lock is used instead. The type of lock (shared or exclusive) can be queried using FileLock.isShared( )


 
PM MAIL   Вверх
Bulat
Дата 30.5.2006, 10:10 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


татарский Нео
***


Профиль
Группа: Завсегдатай
Сообщений: 1701
Регистрация: 22.3.2006
Где: Альметьевск

Репутация: 4
Всего: 57



Beard, 

А собственно это что проверяет? Написал, запустил, сработал у меня if, что и так видно потому как args.length == 0 - true 


--------------------
менеджер по кодеврайтингу  smile 
PM MAIL WWW   Вверх
Beard
Дата 30.5.2006, 11:47 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 228
Регистрация: 5.7.2005
Где: Санкт-Петербург

Репутация: 2
Всего: 9



Так в качестве аргумента надо передать путь до файла, который надо залочить, "что и так видно":
Код

java Locking filepath
 
PM MAIL   Вверх
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Java"
LSD   AntonSaburov
powerOn   tux
javastic
  • Прежде, чем задать вопрос, прочтите это!
  • Книги по Java собираются здесь.
  • Документация и ресурсы по Java находятся здесь.
  • Используйте теги [code=java][/code] для подсветки кода. Используйтe чекбокс "транслит", если у Вас нет русских шрифтов.
  • Помечайте свой вопрос как решённый, если на него получен ответ. Ссылка "Пометить как решённый" находится над первым постом.
  • Действия модераторов можно обсудить здесь.
  • FAQ раздела лежит здесь.

Если Вам помогли, и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, LSD, AntonSaburov, powerOn, tux, javastic.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Java: Общие вопросы | Следующая тема »


 




[ Время генерации скрипта: 0.0465 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.