Java io tmpdir linux

Rational Pi

A description of a platform inconsistency in Java that can cause problems when building file paths that use the temp directory.

The Temp Directory

Java has a way of giving you the path to the temp directory in a platform neutral way. You simply ask the system for the “java.io.tmpdir” property and you’re good to go. Here’s an example of code that does that and prints the result.

The Code

 package tmp; public class TempDir < public static void main(String[] args) < String tmpDir = System.getProperty("java.io.tmpdir"); System.out.println("java.io.tmpdir: [" + tmpDir + "]"); >> 

The Output

On Windows: java.io.tmpdir:[C:\DOCUME~1\joshua\LOCALS~1\Temp\]

On Solaris: java.io.tmpdir:[/var/tmp/]

On Linux: java.io.tmpdir: [/tmp]

On Mac OS X: java.io.tmpdir: [/tmp]

As you can see, it gives you the temp directory that is appropriate to the platform. Now you just use it. Well, almost. Take a look at those paths again. The Linux and Mac OS X ones vary slightly from the others. Not much, but just enough to cause your application to fail if you don’t take precautions. You see it? Yep, the Linux and Mac OS X output don’t end in the file separator (forward slash)! So when you build paths using code like the following…

 String myPath = System.getProperty("java.io.tmpdir") + "some" + File.separator + "place" + File.separator + "somefile.txt"); 

On Solaris: /var/tmp/some/place/somefile.txt

On Linux: /tmpsome/place/somefile.txt

On Mac OS X: /tmpsome/place/somefile.txt

tmp and some get slammed together on Linux and Mac OS X as tmpsome without the file separator between them. This means that if you want to use the java.io.tmpdir property to build a path, you have to check for the file separator at the end of the String and add it if it’s not there.

The other option is just to add the File.separator no matter what when building paths with java.io.tmpdir. In limited tests on Windows, Solaris, Linux and Mac OS X it looks like the operating system handles doubled file separators without problems. It simply swallows the second one and acts as if it was a single file separator.

Real World

So where would this come up? Actually, the reason that I came across it is that I’ve started using the temp directory more often in applications when I need a throw away space. The temp directory is especially useful when used in coordination with the java.io.File.deleteOnExit() method. This method lets you delete a file referenced by a java.io.File reference when the JVM exits. This is very nice when you only need a file for the duration of the running of the application. While I tried to avoid direct file IO in unit testing by using streams and the like, if you are testing classes whose primary function is file IO, then you really need to touch the disk to test effectively. In these cases I usually create a directory within the temp directory and create test files there that will either be deleted in my JUnit tearDown() method or, at the very least, when the JVM exits.

Читайте также:  Двоичное представление числа питон

Bug or Feature?

So why do Linux and Mac OS X vary in this case? Is it a bug in the Linux and Mac OS X implementations of the JDK? Or a bug in the Windows and Solaris implementations? Not according to Sun. I did a little digging and it seems that someone else discovered this little annoyance and reported it as a bug. The state of the issue is “Closed, not a bug”. A feature then? I guess. Touching the system with things like System.getProperty() is always problematic, but it seems that these properties should have been defined a little more rigorously so the inconsistency wouldn’t be there. In any case, hopefully people will run across this “feature” with a search engine hitting on this blog entry instead of at 5pm on a Friday when they try to run their polished Java app on Linux or Mac OS X and it fails due to a missing forward slash.

Resources:

Java Application Development on Linux at Amazon

Java Programming on Linux at Amazon

Keywords:

java java.io.tmpdir System.getProperty temporary temp tmp directory platform consistency inconsistency Linux Mac OS X Windows Solaris

Источник

Переменная окружения для управления java.io.tmpdir?

Я использовал переменную среды TMP для управления такими вещами, как gcc, которые записывают временные файлы, но я не могу найти эквивалент для java createTempFile API. Существует ли такая переменная среды?

Фактическая ссылка: java.sun.com/javase/6/docs/api/java/io/… , java.lang.String, java.io.File) Stackoverflow не делает правильную вещь, когда я помещаю этот URL в (или когда я заменяю скобки на% 28 и% 29). Я знаю, что использование коротких ссылок — отстой, но я подумал, что это лучше, чем вообще отсутствие ссылок.

Читайте также:  Http request type html

все, что я сделал, это перешел по вашей ссылке, скопировал URL из адресной строки моего браузера и вставил его в ваше сообщение, где была ваша короткая ссылка.

6 ответов

Hmmm — так как это обрабатывается JVM, я немного углубился в исходный код OpenJDK VM, думая, что, возможно, что сделано OpenJDK, имитирует то, что сделано на Java 6 и ранее. Не уверен, что есть способ сделать это иначе, чем в Windows.

В Windows функция OpenJDK get_temp_directory() делает вызов API Win32 на GetTempPath() ; это как в Windows, Java отражает значение переменной среды TMP .

В Linux и Solaris, те же функции get_temp_directory() возвращают статическое значение /tmp/ .

Я не знаю, соответствуют ли фактические JDK6 этим точным соглашениям, но поведению на каждой из перечисленных платформ кажется, что они делают.

Чтобы было понятно, вы видите собственный код, который предоставляет значение по умолчанию для свойства «java.io.tmpdir», когда JVM создает объект свойств системы. Это будет переопределено (например) опцией «-Djava.io.tmpdir = . «.

@StephenC, да, в этом-то и дело — ОП искал, как значение по умолчанию для свойства устанавливается в отсутствие его установки самостоятельно (через -Djava.io.tmpdir командной строки -Djava.io.tmpdir для JVM), и если на это значение по умолчанию вообще влияет значение среды. Как наблюдали люди, на Windows , это зависит от TMP переменной окружения, но было неясно, есть ли какая — то неизвестная переменная для других операционных систем. Похоже, что нет, по крайней мере, учитывая то, что мы знаем об OpenJDK.

Хороший ответ, но на Windows GetTempPath() не влияет только переменная среды TMP : msdn.microsoft.com/en-us/library/aa364992%28VS.85%29.aspx

Я видел, что в Solaris Sun JDK значение равно /var/tmp/ (с начальным слешем), для этого есть даже ошибка # 4391434 . А для Mac OS и Linux это /tmp — какой беспорядок!

Источник

Блог Сергея Бородавкина

Только что попробовал запустить в Убунту программу, разработанную под 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, где к ней _руками_ допишут имя каталога и будут дрюкать.

Читайте также:  How can install php

В аутсорсинге ведь не все можно править по своему желанию, если ты еще не забыл 😉

В любом случае, приехавшее имя файла проверяют на
File.isDirectory() и File.exists()
B для конструирования имени файла (не через File(String parent, String child)), всегда используют системо-зависимый разделитель имени файлов, File.separator. В случае если он будет присутсвовать дважды, не произойдет ничего страшного

Тут вот что примечательно: в случае Windows (C:\\Temp\\Pse\\) — действительно не произойдет (поскольку первый слеш, фактически, эскейпит второй), а в Linux (//tmp//pse) — как раз произойдет — exists() вернет false.

Источник

Linux command to get current value of java.io.tmpdir

JDK provides tools with which you can achieve your goal. Using the specified command, you can display the value of a system variable java.io.tmpdir .

The is the number of the java process for which you want to display the value of the system variable. Id of the java process you can get by using the jps tool, which list all java processes running on your machine.

To see all system variables of the java process, please use this command

All JDK tools are located in $JAVA_HOME/bin directory.

java.io.tmpdir is one of java system properties, so its value exists only inside jvm. To find out what is the value of java.io.tmpdir property you can also write a simple program in java. It may look something like this piece of code:

public class JSystemProperties < public static void main(String[] args) < System.getProperties().list(System.out); >> 

The code above will print all java system properties, but you can modify this to print only one system property with name you pass through args array (using System.getProperty(key) method). After you compile this class you can create script (which will run compiled java class) that can be treated as Linux command to get current values of java system properties.

Solution 2

For black box Java applications I’ve deployed in the past, I have sometimes been able to find the value of java.io.tmpdir by executing the following command:

Particularly with tomcat apps, you may get an output like this:

Solution 3

For temp dir: there is a good answer here.

For all environment variable, try env command.

Solution 4

Recommended tool now is jcmd, use it like :

jcmd $pid VM.system_properties | grep java.io.tmpdir 

Источник

Оцените статью