Open file in java linux

Java open java file on linux

Currently I am using the following code for pdf files for example: Windows: Ubuntu Linux: On windows this works just fine for all files. Solution: From the docs java.awt.Desktop.open(File) Question: I’m using Java SE 6 and want to open files in an external process by a predefined program.

Cross-platform way to open a file using Java 1.5

I’m using Java 1.5 and I’d like to launch the associated application to open the file. I know that Java 1.6 introduced the Desktop API , but I need a solution for Java 1.5 .

So far I found a way to do it in Windows:

Runtime.getRuntime().exec(new String[]< "rundll32", "url.dll,FileProtocolHandler", fileName >); 

Is there a cross-platform way to do it? Or at least a similar solution for Linux ?

public static boolean isWindows() < String os = System.getProperty("os.name").toLowerCase(); return os.indexOf("windows") != -1 || os.indexOf("nt") != -1; >public static boolean isMac() < String os = System.getProperty("os.name").toLowerCase(); return os.indexOf("mac") != -1; >public static boolean isLinux() < String os = System.getProperty("os.name").toLowerCase(); return os.indexOf("linux") != -1; >public static boolean isWindows9X()
 if (isLinux()) < cmds.add(String.format("gnome-open %s", fileName)); String subCmd = (exec) ? "exec" : "openURL"; cmds.add(String.format("kfmclient "+subCmd+" %s", fileName)); >else if (isMac()) < cmds.add(String.format("open %s", fileName)); >else if (isWindows() && isWindows9X()) < cmds.add(String.format("command.com /C start %s", fileName)); >else if (isWindows()) < cmds.add(String.format("cmd /c start %s", fileName)); >

JDIC is a library that provides Desktop-like functionality in Java 1.5.

Additionally I would suggest the following implementation using polymorphism:

This way you can add new platform easier by reducing coupling among classes.

 Desktop desktop = Desktop.getDesktop(); desktop.open( aFile ); desktop.imaginaryAction( aFile ); 
package your.pack.name; import java.io.File; public class Desktop < // hide the constructor. Desktop()<>// Created the appropriate instance public static Desktop getDesktop() < String os = System.getProperty("os.name").toLowerCase(); Desktop desktop = new Desktop(); // This uf/elseif/else code is used only once: here if ( os.indexOf("windows") != -1 || os.indexOf("nt") != -1)< desktop = new WindowsDesktop(); >else if ( os.equals("windows 95") || os.equals("windows 98") ) < desktop = new Windows9xDesktop(); >else if ( os.indexOf("mac") != -1 ) < desktop = new OSXDesktop(); >else if ( os.indexOf("linux") != -1 && isGnome() ) < desktop = new GnomeDesktop(); >else if ( os.indexOf("linux") != -1 && isKde() ) < desktop = new KdeDesktop(); >else < throw new UnsupportedOperationException(String.format("The platform %s is not supported ",os) ); >return desktop; > // default implementation :( public void open( File file ) < throw new UnsupportedOperationException(); >// default implementation :( public void imaginaryAction( File file ) < throw new UnsupportedOperationException(); >> // One subclass per platform below: // Each one knows how to handle its own platform class GnomeDesktop extends Desktop < public void open( File file )< // Runtime.getRuntime().exec: execute gnome-open > public void imaginaryAction( File file ) < // Runtime.getRuntime().exec:gnome-something-else > > class KdeDesktop extends Desktop < public void open( File file )< // Runtime.getRuntime().exec: kfmclient exec > public void imaginaryAction( File file ) < // Runtime.getRuntime().exec: kfm-imaginary.****;file>> > class OSXDesktop extends Desktop < public void open( File file )< // Runtime.getRuntime().exec: open > public void imaginaryAction( File file ) < // Runtime.getRuntime().exec: wow!! > > class WindowsDesktop extends Desktop < public void open( File file )< // Runtime.getRuntime().exec: cmd /c start > public void imaginaryAction( File file ) < // Runtime.getRuntime().exec: ipconfig /relese /c/d/e >> class Windows9xDesktop extends Desktop < public void open( File file )< //Runtime.getRuntime().exec: command.com /C start > public void imaginaryAction( File file) < //Runtime.getRuntime().exec: command.com /C otherCommandHere > > 

This is only an example, in real life is not worth to create a new class only to parametrize a value ( the command string %s ) But let’s do imagine that each method performs another steps in platform specific way.

Читайте также:  Html hint on div

Doing this kind of approach, may remove unneeded if/elseif/else constructs that with time may introduce bugs ( if there are 6 of these in the code and a change is neede, you may forget to update one of them, or by copy/pasting you may forget to change the command to execute)

Just as an addition: Rather than gnome-open , use xdg-open . It’s part of the XdgUtils, which are in turn part of the LSB Desktop support package (starting with 3.2).

You can (should) still use gnome-open as a fallback, but xdg-open will also work on non-GNOME desktops.

How to Uninstall Java on Mac, Method 1: Using Terminal for Uninstalling Java on Mac. For the purpose of uninstalling Java on Mac, open the terminal with the Administrator credentials and type the following “ rm ” command to remove the specified “ JavaAppletPlugin.plugin ” directory: % sudo rm — fr / Library / Internet\ Plug — Ins / …

Open an eml file with java in linux

I am trying to open my created .eml file with java in linux. Currently I am using the following command:

Desktop.getDesktop().open(emlFile); 

I create the eml file as shown in this example. This works for my windows system, but an error occurs in linux ubuntu 12.04.

(process:19386): gnome-vfs-modules-WARNING **: Could not initialize inotify java.io.IOException: Failed to show URI:file:/home/usr/workspace/programm/eml/mail.eml at sun.awt.X11.XDesktopPeer.launch(Unknown Source) at sun.awt.X11.XDesktopPeer.open(Unknown Source) at java.awt.Desktop.open(Unknown Source) 

From the docs java.awt.Desktop.open(File)

Throws IOException — if the specified file has no associated application or the associated application fails to be launched

Java — How to open a folder path on windows and linux, @TechnoCraft it does help, very useful post, thanks. But some how I figured out that the Desktop.getDesktop is depended upon some external libraries (Gnome libraries, that’s what the post says) but as i haven’t found anything else so i will go with this approach assuming that the client linux machine will have those …

Java SE 6: How to open files externally by Runtime.getRuntime().exec() on Ubuntu Linux?

I’m using Java SE 6 and want to open files in an external process by a predefined program. Currently I am using the following code for pdf files for example:

public static Process openFile(File file) < return Runtime.getRuntime().exec("C:/Program Files (x86)/Adobe/Reader 10.0/Reader/AcroRd32.exe \""+file.getAbsolutePath()+"\""); >
public static Process openFile(File file) < return Runtime.getRuntime().exec("/usr/bin/evince \""+file.getAbsolutePath()+"\""); >

On windows this works just fine for all files. But on ubuntu, as soon as there’s a space within the file path , it tries to open multiple files. Here’s an example:

contract.pdf -> works on windows and ubuntu contract 1 (copy).pdf -> works only on windows, ubuntu tries to open 3 different files (contract, 1, and (copy).pdf) 

What special character do I need to tell ubuntu that it should handle file paths with spaces as one file ?

Thanks for your help in advance! Best regards

I would try using Desktop.open

Launches the associated application to open the file.

If the specified file is a directory, the file manager of the current platform is launched to open it.

return Runtime.getRuntime().exec(new String[]< "/usr/bin/evince", file.getAbsolutePath() >); 

Linux — How to run an application on a specific Java, How can I run an application with a specific Java version? I have three Java versions intstalled: myuser@mysystem:~$ sudo update-alternatives —config java There are 3 choices for the alternative Stack Overflow. About; Products For Teams; Stack Overflow Public questions & answers; Stack Overflow for Teams …

Читайте также:  Python unittest assertraises примеры

Open Browser window from Java program

I have an application written in Java. It is designed to run on a Linux box standalone. I am trying to spawn a new firefox window. However, firefox never opens. It always has a shell exit code of 1. I can run this same code with gnome-terminal and it opens fine.

So, here is its initialization process:

  1. Start X «Xorg :1 -br -terminate -dpms -quiet vt7»
  2. Start Window Manager «metacity —display=:1 —replace»
  3. Configure resources «xrdb -merge /etc/X11/Xresources»
  4. Become a daemon and disconnect from controlling terminal

Once the program is up an running, there is a button the user can click that should spawn a firefox window. Here is my code to do that. Remember X is running on display :1.

 public boolean openBrowser() < try < Process oProc = Runtime.getRuntime().exec( "/usr/bin/firefox --display=:1" ); int bExit = oProc.waitFor(); // This is always 1 for some reason return true; >catch ( Exception e ) < oLogger.log( Level.WARNING, "Open Browser", e ); return false; >> 

If you can narrow it down to Java 6, you can use the desktop API:

Should look something like:

 if (Desktop.isDesktopSupported()) < Desktop desktop = Desktop.getDesktop(); if (desktop.isSupported(Desktop.Action.BROWSE)) < try < desktop.browse(new URI("http://localhost")); >catch(IOException ioe) < ioe.printStackTrace(); >catch(URISyntaxException use) < use.printStackTrace(); >> > 

Invoking it is very easy, just go

new BrowserLauncher().openURLinBrowser("http://www.google.com"); 

after having read the various answers and various comments(from questioner), here’s what I would do

1) try this java approach http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ProcessBuilder.html

ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2"); Map env = pb.environment(); env.put("VAR1", "myValue"); env.remove("OTHERVAR"); env.put("VAR2", env.get("VAR1") + "suffix"); pb.directory("myDir"); Process p = pb.start(); 

see more about this class:

2) try doing this(launching firefox) from C/C++/ruby/python and see if that is succeeding.

3) if all else fails, I would launch a shell program and that shell program would launch firefox!!

You might have better luck if you read and display the standard output/error streams, so you can catch any error message firefox may print.

How to Run Java from Command-line in Linux, To run the java program in Linux, we need to verify if Java Development Kit (JDK) is available in the system and its version. To confirm it, type the following command: $ javac -version ( Javac command-line tool is used for the compilation of java programs) The Javac command tool is not available in my system.

Источник

Как запустить jar в Linux

Java — это кроссплатформенный язык программирования, благодаря которому программы, написанные один раз, можно запускать в большинстве операционных систем: в Windows, Linux и даже MacOS. И всё это без каких-либо изменений.

Но программы, написанные на Java, распространяются в собственном формате .jar, и для их запуска необходимо специальное ПО — Java-машина. В этой небольшой статье мы рассмотрим, как запустить jar-файл в Linux.

Как запустить jar Linux

Как я уже сказал, для запуска jar-файлов нам необходимо, чтобы на компьютере была установлена Java-машина. Если вы не собираетесь ничего разрабатывать, вам будет достаточно Java Runtime Environment или JRE. Что касается версии, то, обычно, большинство программ работают с 7 или 8 версией. Если нужна только восьмая, то разработчики прямо об этом сообщают. Посмотреть версию Java и заодно убедиться, что она установлена в вашей системе, можно с помощью команды:

Читайте также:  Html change all text font

У меня установлена восьмая версия, с пакетом обновлений 171. Если вы получаете ошибку, что команда не найдена, то это значит, что вам нужно установить java. В Ubuntu OpenJDK JRE можно установить командой:

sudo apt install openjdk-8-jre

Если вы хотите скомпилировать пример из этой статьи, то вам понадобиться не JRE, а JDK, её можно установить командой:

sudo apt install openjdk-8-jdk-headless

Чтобы узнать, как установить Java в других дистрибутивах, смотрите статью по ссылке выше. Когда Java будет установлена, вы можете очень просто запустить любой jar-файл в Linux, передав путь к нему в качестве параметра Java-машине. Давайте для примера создадим небольшое приложение:

public class Main public static void main(String[] args) System.out.println(» Losst test app! «);
>
>

Затем скомпилируем наше приложение в jar-файл:

javac -d . Main.java
jar cvmf MANIFEST.MF main.jar Main.class

Теперь можно запустить наш jar-файл командой java с параметром -jar:

Таким образом вы можете запустить любой jar-файл, который собран для вашей версии Java. Но не очень удобно каждый раз открывать терминал и прописывать какую-либо команду. Хотелось бы запускать программу по щелчку мышки или как любую другую Linux-программу — по имени файла.

Если мы дадим программе право на выполнение:

И попытаемся её запустить, то получим ошибку:

Чтобы её исправить, нам понадобиться пакет jarwrapper:

sudo apt install jarwrapper

Теперь можно запускать java в Linux по щелчку мыши или просто командой.

Выводы

В этой небольшой статье мы рассмотрели, как запустить jar Linux с помощью java-машины, а также как упростить команду запуска. Если у вас остались вопросы, спрашивайте в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

How to open a File in Java

How to open a File in Java

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Sometimes we have to open a file in java program. java.awt.Desktop can be used to open a file in java. Desktop implementation is platform dependent, so first, we should check if the operating system supports Desktop or not. This class looks for the associated application registered to the current platform to open a file.

Java Open File

java open file, how to open a file in java

Let’s have a look at the simple java open file program. If we try to open a file that doesn’t exist, it will throw java.lang.IllegalArgumentException . Let’s see Desktop class example for java open file. JavaOpenFile.java

package com.journaldev.files; import java.awt.Desktop; import java.io.File; import java.io.IOException; public class JavaOpenFile < public static void main(String[] args) throws IOException < //text file, should be opening in default text editor File file = new File("/Users/pankaj/source.txt"); //first check if Desktop is supported by Platform or not if(!Desktop.isDesktopSupported())< System.out.println("Desktop is not supported"); return; >Desktop desktop = Desktop.getDesktop(); if(file.exists()) desktop.open(file); //let's try to open PDF file file = new File("/Users/pankaj/java.pdf"); if(file.exists()) desktop.open(file); > > 

When you run the above program, the text file will be opened in the default text editor. Similarly, a PDF file will be opened in adobe acrobat reader. If there are no application associated with given file type or the application is failed to launch, open method throws java.io.IOException . That’s all for a simple program to open a file in java.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us

Источник

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