- Блог Сергея Бородавкина
- java.io.tmpdir в Windows и Linux
- 4 коммент. | добавить комментарий :: java.io.tmpdir в Windows и Linux
- java.io.tmpdir Example
- Change the default value of java.io.tmpdir
- Create a temporary file
- Windows temp directory details (Java)
- 7 Answers 7
- How to create a temporary directory/folder in Java?
- 18 Answers 18
- Переменная окружения для управления java.io.tmpdir?
- 7 ответов
- Похожие вопросы:
Блог Сергея Бородавкина
java.io.tmpdir в Windows и Linux
Только что попробовал запустить в Убунту программу, разработанную под Windows. Ну что сказать — был удивлен.
System.getProperty(«java.io.tmpdir») в Windows возвращает что-то наподобие:
А в Linux мне приходит вот что:
Обратите внимание — в первом случае завершающий слеш есть, а во втором — нет, что требует дополнительной проверки в коде.
«Java: написано однажды — тестируем везде» (c)
4 коммент. | добавить комментарий :: java.io.tmpdir в Windows и Linux
Да потому что нехрен генерировать имена файлов руками, конструктор File(String parent, String child) для чего придуман?
А если нужно просто временный файл создать, для этого правильнее использовать File.createTempFile(String prefix, String suffix).
Та шо ж ты аггрессивный такой!
Мне просто нужна строка с этой проперти, причем со слешом в конце. Она потом пойдет в либу заказчика, лежащую в Trunk, где к ней _руками_ допишут имя каталога и будут дрюкать.
В аутсорсинге ведь не все можно править по своему желанию, если ты еще не забыл 😉
В любом случае, приехавшее имя файла проверяют на
File.isDirectory() и File.exists()
B для конструирования имени файла (не через File(String parent, String child)), всегда используют системо-зависимый разделитель имени файлов, File.separator. В случае если он будет присутсвовать дважды, не произойдет ничего страшного
Тут вот что примечательно: в случае Windows (C:\\Temp\\Pse\\) — действительно не произойдет (поскольку первый слеш, фактически, эскейпит второй), а в Linux (//tmp//pse) — как раз произойдет — exists() вернет false.
java.io.tmpdir Example
Posted by: Sotirios-Efstathios Maneas in io September 17th, 2014 0 Views
In this tutorial we will discuss about the java.io.tmpdir system property. The java.io.tmpdir system property indicates the temporary directory used by the Java Virtual Machine (JVM) to create and store temporary files.
The default value is typically «/tmp» , or «/var/tmp» on Unix-like platforms. On Microsoft Windows systems the java.io.tmpdir property is typically «C:\\WINNT\\TEMP» .
During your application’s execution, you can acquire and print the value of the java.io.tmpdir system property, using the following code:
Change the default value of java.io.tmpdir
In case you want to alter the java.io.tmpdir system property, you can make use of the -Djava.io.tmpdir argument and specify your own temporary directory. For example:
In this way, you alter the value of the java.io.tmpdir system property, during the initialization of the Java Virtual Machine (JVM). Otherwise, you can use the following snippet, in order to change the value of the java.io.tmpdir system property:
Create a temporary file
Java provides two static methods in order to create temporary files via the File class:
This method creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name.
This method creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name. Invoking this method is equivalent to invoking the method createTempFile(prefix, suffix, null) .
A sample example that creates a number of temporary files is shown below:
A sample execution is shown below:
Notice that the files created by the createTempFile method have different names during each execution.
Windows temp directory details (Java)
I’m writing a program that needs a generic temp folder. I’m trying to find details about the Windows Temp folders. There are two paths that I know about —
In each user directory under AppData\Local\Temp\ This may change depending Windows version?
In the system folder under Temp\ (C:\Windows\Temp)
I’m wondering exactly what Windows does to each of these. If Windows deletes files from either location, when does it do so? How can/should I use these directories for my programming?
EDIT: I have a bigger problem actually — Because of a certain engine I’m running indirectly with my program, which uses files I’m creating in a temp directory, I need a temp directory that doesn’t use whitespace characters in the path. Java’s System.getProperty(«java.io.tmpdir») on Windows gives me the temp that’s in the user directory, which on XP is under «Documents and Settings. » Not good. Any suggestions? This is why I’m wondering about the C:\Windows\Temp\ directory.
7 Answers 7
Not quite. There is a user and system folder, the default location of which varies according the windows version, system folder name, and indeed in older versions of windows was the same for both the user and system case. However, these defaults can be over-ridden (they are on the system I’m using now, where they aren’t on the same drive as the system folder).
The locations are stored in system variables. Some frameworks (.NET, VB6 and no doubt others) give you convient ways to find the paths rather than having to look up the system variable (e.g. System.IO.Path.GetTempPath in .NET).
Windows does not clean up the temporary folder for you (which is why it’s worth blasting out old files it every few months on your own machine), it’s up to you to play nice. Create a file or files unlikely to step on the names any other software is using (they should take care to do the same, and so any name should do, but it’s always good to assume the worse of other code on the system), and delete files when you’re done (or on application exit at least).
How to create a temporary directory/folder in Java?
Is there a standard and reliable way of creating a temporary directory inside a Java application? There’s an entry in Java’s issue database, which has a bit of code in the comments, but I wonder if there is a standard solution to be found in one of the usual libraries (Apache Commons etc.) ?
18 Answers 18
If you are using JDK 7 use the new Files.createTempDirectory class to create the temporary directory.
Before JDK 7 this should do it:
You could make better exceptions (subclass IOException) if you want.
The Google Guava library has a ton of helpful utilities. One of note here is the Files class. It has a bunch of useful methods including:
This does exactly what you asked for in one line. If you read the documentation here you’ll see that the proposed adaptation of File.createTempFile(«install», «dir») typically introduces security vulnerabilities.
If you need a temporary directory for testing and you are using jUnit, @Rule together with TemporaryFolder solves your problem:
The TemporaryFolder Rule allows creation of files and folders that are guaranteed to be deleted when the test method finishes (whether it passes or fails)
Update:
If you are using JUnit Jupiter (version 5.1.1 or greater), you have the option to use JUnit Pioneer which is the JUnit 5 Extension Pack.
For example, the following test registers the extension for a single test method, creates and writes a file to the temporary directory and checks its content.
Update 2:
The @TempDir annotation was added to the JUnit Jupiter 5.4.0 release as an experimental feature. Example copied from the JUnit 5 User Guide:
Naively written code to solve this problem suffers from race conditions, including several of the answers here. Historically you could think carefully about race conditions and write it yourself, or you could use a third-party library like Google’s Guava (as Spina’s answer suggested.) Or you could write buggy code.
But as of JDK 7, there is good news! The Java standard library itself now provides a properly working (non-racy) solution to this problem. You want java.nio.file.Files#createTempDirectory(). From the documentation:
Creates a new directory in the specified directory, using the given prefix to generate its name. The resulting Path is associated with the same FileSystem as the given directory.
The details as to how the name of the directory is constructed is implementation dependent and therefore not specified. Where possible the prefix is used to construct candidate names.
This effectively resolves the embarrassingly ancient bug report in the Sun bug tracker which asked for just such a function.
Переменная окружения для управления java.io.tmpdir?
Я использовал переменную окружения TMP для управления такими вещами, как то, где gcc записывает свои временные файлы, но я не могу найти эквивалент для java createTempFile API.
Существует ли такая переменная окружения?
7 ответов
я получаю сообщение об ошибке невозможно определить место установки. Пожалуйста, установите переменную окружения ‘EBSDIR’ в каталог установки. может ли кто-нибудь сказать мне, что такое переменная окружения EBSDIR и для чего она используется? какой путь установки он запрашивает? спасибо
Я вижу, что существует переменная окружения SVN_EDITOR для определения того, какой редактор использовать с subversion, а также переменная окружения SVN_MERGE для объединения файлов. Существует ли переменная окружения для определения инструмента дифференцирования ?
Согласно документам java.io.File Java
Каталог временных файлов по умолчанию задается системным свойством java.io.tmpdir. В системах UNIX значение этого свойства по умолчанию обычно равно » /tmp «или «/var/tmp»;, в системах Microsoft Windows оно обычно равно»c:\temp». При вызове виртуальной машины Java этому системному свойству может быть присвоено другое значение, но программные изменения этого свойства не гарантированно окажут какое-либо влияние на временный каталог, используемый этим методом.
Чтобы указать системное свойство java.io.tmpdir , можно вызвать JVM следующим образом:
По умолчанию это значение должно исходить из переменной окружения TMP в системах Windows
Хммм-поскольку это обрабатывается JVM, я немного углубился в исходный код OpenJDK VM, думая, что, возможно, то, что сделано OpenJDK, имитирует то, что сделано Java 6 и ранее. Это не обнадеживает, что есть способ сделать это иначе, чем на Windows.
На Windows функция OpenJDK get_temp_directory() вызывает Win32 API на GetTempPath() ; именно так на Windows Java отражает значение переменной окружения TMP .
В Linux и Solaris одни и те же функции get_temp_directory() возвращают статическое значение /tmp/ .
Я не знаю, следует ли фактический JDK6 этим точным соглашениям, но по поведению на каждой из перечисленных платформ кажется, что они это делают.
Вы можете установить переменную окружения _JAVA_OPTIONS . Например, в bash это сделало бы трюк:
Я вставил это в свой сценарий входа в систему bash, и, похоже,это сработало.
Я пытаюсь настроить путь к экземпляру osgi и папкам конфигурации, чтобы запустить мое приложение Eclipse RCP. Для этого я настраиваю следующее В теге в файле jnlp:
Я пытаюсь настроить переменную окружения через Python : os.environ[myRoot]=/home/myName os.environ[subDir]=$myRoot/subDir Я ожидаю, что переменная окружения subDir будет содержать /home/myname/subDir , однако она содержит строку ‘$myRoot/subDir’ . Как мне получить эту функциональность? (Более.
Это не переменная окружения, но все же дает вам контроль над временным каталогом:
Чтобы было ясно, что здесь происходит:
Рекомендуемый способ установить расположение временного каталога — установить системное свойство «java.io.tmpdir», например, предоставив команде java опцию -Djava.io.tmpdir=/mytempdir . Отель также могут быть изменены в программе с помощью вызова System.setProperty(«java.io.tmpdir», «/mytempdir) . вопросы по модулю изолированной программной среде безопасности.
Если вы явно не зададите свойство » java.io.tmpdir » при запуске, то JVM инициализирует его значением по умолчанию для конкретной платформы . Для Windows значение по умолчанию получается вызовом метода Win32 API. Для Linux / Solaris значение по умолчанию, по-видимому, жестко привязано. Для других JVMs это может быть что-то другое.
Эмпирически переменная окружения «TMP» работает на Windows (с текущим JVMs), но не на других платформах. Если вы заботитесь о переносимости, вы должны явно установить системное свойство.
Используйте нижеприведенную команду на UNIX terminal :
При этом будут отображены все свойства java и системные настройки. В этом случае ищите значение java.io.tmpdir .
Похожие вопросы:
Я пытаюсь изменить каталог java.io.tmpdir с помощью этой команды java -Djava.io.tmpdir=/temporary Но это не удается, и отображается ‘Usage’ команды java. Я делаю это в машине RHEL. Заранее спасибо Я.
Почему нам нужно создать файл nant.bat в каталоге, включенном в системную переменную окружения PATH? Что на самом деле представляет собой эта переменная окружения Path system? А что, если я этого не.
Я столкнулся с проблемой установки некоторых пакетов npm для приложения на Windows 10. В частности, gyp, похоже, вызывает проблемы, потому что он не может найти исполняемый файл python. Вот часть.
я получаю сообщение об ошибке невозможно определить место установки. Пожалуйста, установите переменную окружения ‘EBSDIR’ в каталог установки. может ли кто-нибудь сказать мне, что такое переменная.
Я вижу, что существует переменная окружения SVN_EDITOR для определения того, какой редактор использовать с subversion, а также переменная окружения SVN_MERGE для объединения файлов. Существует ли.
Я пытаюсь настроить путь к экземпляру osgi и папкам конфигурации, чтобы запустить мое приложение Eclipse RCP. Для этого я настраиваю следующее В теге в файле jnlp: