As i am doing a backporting task i need to get an application from Android 9 to Android 5.1 to work.
It contains a lot of functionalities related to files like Exporting and importing of Json files and creating directories.
Is there an alternative to the File functionalities found in Java 8, or a way to get them in Java 7 or some library that backports those as i just cannot find a solution to this.
Thanks!
Here are is a method as an example of what i would like to backport.
public static void exportLogcats(final Context context, final List<BootEvent> events,
final String outputFolder) throws IOException {
if (events == null) {
return;
}
final String sourceFolder =
new File(context.getFilesDir(), LOGCAT_FOLDER).getAbsolutePath();
final Path outputPath;
outputPath = Paths.get(outputFolder);
deleteDirectory(outputPath);
Files.createDirectories(outputPath);
for (BootEvent event : events) {
final String filename = event.getLogcatFilename();
try {
final Path source;
source = Paths.get(sourceFolder, filename);
final Path destination = Paths.get(outputFolder, filename);
Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException | NullPointerException e) {
Log.e(LOG_TAG, "Could not copy file " + filename, e);
}
}
}
The problem is that calls like
.get on Paths, .createDirectories or .copy on Files does not work on API level 22
I have those java files:
//i2cjni.java
public class i2cJNI {
static {
try {
System.loadLibrary("i2cbrdg");
}
catch(UnsatisfiedLinkError e) {
System.err.println("Native code library failed to load. \n" + e);
System.exit(1);
}
}
public final static native long U2C_GetDeviceCount();
public final static native long U2C_OpenDevice(long jarg1);
public final static native long U2C_CloseDevice(long jarg1);
...
}
//i2c.java
public class i2c {
public static SWIGTYPE_p_BYTE U2C_GetDeviceCount() {
return new SWIGTYPE_p_BYTE(i2cJNI.U2C_GetDeviceCount(), true);
}
//I2CBoard.java
public class I2CBoard extends i2c{
public static void main(String[] args) {
SWIGTYPE_p_BYTE nDevice = new SWIGTYPE_p_BYTE();
i2c.U2C_OpenDevice(nDevice);
SWIGTYPE_p_BYTE mDevice = i2c.U2C_GetDeviceCount();
System.out.println("mDevice: " + mDevice);
}
}
-I have set the native library path like this:
i2c_wrapper/Native library location: ro.i2c.mirela/os/x86_64
and in the same way to the rest of them: JRE System Library, Plug-in Dependencies, ro.i2c.mirela/os(class folder) and i2c_wrapper
-I have added this folder to the project:
os/x86_64/i2c_wrapper.dll
os/x86_64/i2cbrdg.dll
os/x86_64/U2CCommon.dll
-when I try to call the U2C_GetDeviceCount() function and so on, I get this error. Any ideas?
Exception in thread "main" java.lang.UnsatisfiedLinkError: ro.i2c.mirela.board.i2cJNI.U2C_OpenDevice(J)J
at ro.i2c.mirela.board.i2cJNI.U2C_OpenDevice(Native Method)
at ro.i2c.mirela.board.i2c.U2C_OpenDevice(i2c.java:28)
at ro.i2c.mirela.board.I2CBoard.main(I2CBoard.java:8)
that like is a link error,may be your .c file function name is not right,maybe you should post your .c
file
I have done set up a NAS server using NAS4Free and share a folder at:
\\NAS_SERVER_IP/SHARE_FOLDER_NAME
In SHARE_FOLDER_NAME directory contains resource files need to share to multiple clients
Now ,from clients , can I using Java to access (read/write) directly file from NAS server without mount shared folder to local clients
Copied from here, but changed the api call argument.
connecting to shared folder in windows with java
String url = "smb://[NAS server-IP or hostname]/file-or-directory-path";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("[company network domain]", "user", "password");
SmbFile dir = new SmbFile(url, auth);
for (SmbFile f : dir.listFiles())
{
System.out.println(f.getName());
}
For observing file/dir changes using JDK 6, you could use:
WatchService for Java 6
For JDK 7, WatchService is part of NIO package:
http://java.dzone.com/news/how-watch-file-system-changes
Finally, this one works with JDK6 as well. This way, we could observe file/dir changes in windows shared drivers without mounting/mapping them as a drive.
I've used following jars in classpath: commons-collections-4.4.0, commons-logging-1.1.2, commons-logging-api-1.1.2, commons-net-3.3, commons-vfs2-2.0, httpclient-4.3.1, jackrabbit-standalone-2.6.5, jcifs-1.3.17, jsch-0.1.51
import org.apache.commons.vfs2.FileChangeEvent;
import org.apache.commons.vfs2.FileListener;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.VFS;
import org.apache.commons.vfs2.impl.DefaultFileMonitor;
public class NFSChangeObserver
{
public static void main(String[] args) throws FileSystemException
{
/** need a non-daemon thread, because <code>DefaultFileMonitor</code> is internally marked as a daemon thread.
*/
Thread t = new Thread(new Runnable() {
#Override
public synchronized void run()
{
try
{
while(1!=2)
wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}});
t.start();
FileSystemManager manager = VFS.getManager();
FileObject file = manager.resolveFile("\\\\[server-hostname]\\[directory-path]");
DefaultFileMonitor fm = new DefaultFileMonitor(new FileListener()
{
#Override
public void fileChanged(final FileChangeEvent fileChangeEvt) throws Exception
{
System.out.println("#" + System.currentTimeMillis() + ": " + fileChangeEvt.getFile().getName() + " changed .." );
}
#Override
public void fileCreated(FileChangeEvent fileChangeEvt) throws Exception
{
System.out.println("#" + System.currentTimeMillis() + ": " + fileChangeEvt.getFile().getName() + " created .." );
}
#Override
public void fileDeleted(FileChangeEvent fileChangeEvt) throws Exception
{
System.out.println("#" + System.currentTimeMillis() + ": " + fileChangeEvt.getFile().getName() + " deleted .." );
}
});
fm.setDelay(5000);
fm.addFile(file);
FileObject[] children = file.getChildren();
for(FileObject child : children)
{
System.out.println(child.getURL());
}
fm.start();
}
}
i see this question has been posted many times but it has been solved with adding
-Djava.library.path="./path" to the VM runtime options.
I have to build an app in JAVA which uses the JNotify classes.
this is the sample code:
package test;
import net.contentobjects.jnotify.JNotify;
import net.contentobjects.jnotify.JNotifyListener;
/**
*
* #author
*/
public class Test {
public void jnotifydemo() throws Exception {
// path to watch
String path = System.getProperty("user.home");
// watch mask, specify events you care about,
// or JNotify.FILE_ANY for all events.
int mask = JNotify.FILE_CREATED
| JNotify.FILE_DELETED
| JNotify.FILE_MODIFIED
| JNotify.FILE_RENAMED;
// watch subtree?
boolean watchSubtree = true;
// add actual watch
int watchID = JNotify.addWatch(path, mask, watchSubtree, new Listener());
// sleep a little, the application will exit if you
// don't (watching is asynchronous), depending on your
// application, this may not be required
Thread.sleep(1000000);
// to remove watch the watch
boolean res = JNotify.removeWatch(watchID);
if (!res) {
// invalid watch ID specified.
}
}
class Listener implements JNotifyListener {
public void fileRenamed(int wd, String rootPath, String oldName,
String newName) {
print("renamed " + rootPath + " : " + oldName + " -> " + newName);
}
public void fileModified(int wd, String rootPath, String name) {
print("modified " + rootPath + " : " + name);
}
public void fileDeleted(int wd, String rootPath, String name) {
print("deleted " + rootPath + " : " + name);
}
public void fileCreated(int wd, String rootPath, String name) {
print("created " + rootPath + " : " + name);
}
void print(String msg) {
System.err.println(msg);
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
System.out.println("Hello World");
new Test().jnotifydemo();
}
}
When i run this i get:
Error loading library, java.library.path=C:\Program Files\Java\jdk1.6.0_26\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Windows\system32;(continues)
Exception in thread "main" java.lang.UnsatisfiedLinkError: no jnotify in java.library.path
I have setup a Netbeans project and added the JAR file to the project so that the JAR is correctly in the lib/ folder of my project and everything is set in NETBEANS.
This correctly works if is setup the -Djava.library.path="./path" argument of the java VM, but if i imported my lib in NETBEANS that should be included in the path automatically.
I am doing something wrong or it is necessary to put every .jar in the classpath system variable? I would like to release this app so it can run on other systems that does not have JNotify in their libs.
Thanks
I am using Netbeans 7.2 on Win 7 32Bit
You are messing java jar files as library which has to be added only in netbeans classpath:
Simply in NetBeans on project properties click and adjust Library having your JAR file.
For the native libraries (so,dll,...) you need to have set: -Djava.library.path. As you did in your question.
So you have 2 steps:
1. from http://sourceforge.net/projects/jnotify/files/jnotify/jnotify-0.94/jnotify-lib-0.94.zip/download add jnotify-0.94.jar to your libraries as in picture above (this will update your classpath automatically)
2. jnotify.dll, or jnotify_64bit.dll for 64-bit windows place is some directory and ad this to your -Djava.library.path - add this to VM option of the projects property
Can someone point me in the right direction on how to open the default web browser and set the page to "www.example.com" thanks
java.awt.Desktop is the class you're looking for.
import java.awt.Desktop;
import java.net.URI;
// ...
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().browse(new URI("http://www.example.com"));
}
For me solution with Desktop.isDesktopSupported() doesn't work (windows 7 and ubuntu). Please try this to open browser from java code:
Windows:
Runtime rt = Runtime.getRuntime();
String url = "http://stackoverflow.com";
rt.exec("rundll32 url.dll,FileProtocolHandler " + url);
Mac
Runtime rt = Runtime.getRuntime();
String url = "http://stackoverflow.com";
rt.exec("open " + url);
Linux:
Runtime rt = Runtime.getRuntime();
String url = "http://stackoverflow.com";
String[] browsers = { "google-chrome", "firefox", "mozilla", "epiphany", "konqueror",
"netscape", "opera", "links", "lynx" };
StringBuffer cmd = new StringBuffer();
for (int i = 0; i < browsers.length; i++)
if(i == 0)
cmd.append(String.format( "%s \"%s\"", browsers[i], url));
else
cmd.append(String.format(" || %s \"%s\"", browsers[i], url));
// If the first didn't work, try the next browser and so on
rt.exec(new String[] { "sh", "-c", cmd.toString() });
If you want to have multiplatform application, you need to add operation system checking(for example):
String os = System.getProperty("os.name").toLowerCase();
Windows:
os.indexOf("win") >= 0
Mac:
os.indexOf("mac") >= 0
Linux:
os.indexOf("nix") >=0 || os.indexOf("nux") >=0
Here is my code. It'll open given url in default browser (cross platform solution).
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class Browser {
public static void main(String[] args) {
String url = "http://www.google.com";
if(Desktop.isDesktopSupported()){
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(new URI(url));
} catch (IOException | URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("xdg-open " + url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
As noted in the answer provided by Tim Cooper, java.awt.Desktop has provided this capability since Java version 6 (1.6), but with the following caveat:
Use the isDesktopSupported() method to determine whether the Desktop API is available. On the Solaris Operating System and the Linux platform, this API is dependent on Gnome libraries. If those libraries are unavailable, this method will return false.
For platforms which do not support or provide java.awt.Desktop, look into the BrowserLauncher2 project. It is derived and somewhat updated from the BrowserLauncher class originally written and released by Eric Albert. I used the original BrowserLauncher class successfully in a multi-platform Java application which ran locally with a web browser interface in the early 2000s.
Note that BrowserLauncher2 is licensed under the GNU Lesser General Public License. If that license is unacceptable, look for a copy of the original BrowserLauncher which has a very liberal license:
This code is Copyright 1999-2001 by Eric Albert (ejalbert#cs.stanford.edu) and may be redistributed or modified in any form without restrictions as long as the portion of this comment from this paragraph through the end of the comment is not removed. The author requests that he be notified of any application, applet, or other binary that makes use of this code, but that's more out of curiosity than anything and is not required. This software includes no warranty. The author is not repsonsible for any loss of data or functionality or any adverse or unexpected effects of using this software.
Credits:
Steven Spencer, JavaWorld magazine (Java Tip 66)
Thanks also to Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea Cantatore, Larry Barowski, Trevor Bedzek, Frank Miedrich, and Ron Rabakukk
Projects other than BrowserLauncher2 may have also updated the original BrowserLauncher to account for changes in browser and default system security settings since 2001.
You can also use the Runtime to create a cross platform solution:
import java.awt.Desktop;
import java.net.URI;
public class App {
public static void main(String[] args) throws Exception {
String url = "http://stackoverflow.com";
if (Desktop.isDesktopSupported()) {
// Windows
Desktop.getDesktop().browse(new URI(url));
} else {
// Ubuntu
Runtime runtime = Runtime.getRuntime();
runtime.exec("/usr/bin/firefox -new-window " + url);
}
}
}
Hope you don't mind but I cobbled together all the helpful stuff, from above, and came up with a complete class ready for testing...
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class MultiBrowPop {
public static void main(String[] args) {
OUT("\nWelcome to Multi Brow Pop.\nThis aims to popup a browsers in multiple operating systems.\nGood luck!\n");
String url = "http://www.birdfolk.co.uk/cricmob";
OUT("We're going to this page: "+ url);
String myOS = System.getProperty("os.name").toLowerCase();
OUT("(Your operating system is: "+ myOS +")\n");
try {
if(Desktop.isDesktopSupported()) { // Probably Windows
OUT(" -- Going with Desktop.browse ...");
Desktop desktop = Desktop.getDesktop();
desktop.browse(new URI(url));
} else { // Definitely Non-windows
Runtime runtime = Runtime.getRuntime();
if(myOS.contains("mac")) { // Apples
OUT(" -- Going on Apple with 'open'...");
runtime.exec("open " + url);
}
else if(myOS.contains("nix") || myOS.contains("nux")) { // Linux flavours
OUT(" -- Going on Linux with 'xdg-open'...");
runtime.exec("xdg-open " + url);
}
else
OUT("I was unable/unwilling to launch a browser in your OS :( #SadFace");
}
OUT("\nThings have finished.\nI hope you're OK.");
}
catch(IOException | URISyntaxException eek) {
OUT("**Stuff wrongly: "+ eek.getMessage());
}
}
private static void OUT(String str) {
System.out.println(str);
}
}
Its very simple just write below code:
String s = "http://www.google.com";
Desktop desktop = Desktop.getDesktop();
desktop.browse(URI.create(s));
or if you don't want to load URL then just write your browser name into string values like,
String s = "chrome";
Desktop desktop = Desktop.getDesktop();
desktop.browse(URI.create(s));
it will open browser automatically with empty URL after executing a program
I recast Brajesh Kumar's answer above into Clojure as follows:
(defn open-browser
"Open a new browser (window or tab) viewing the document at this `uri`."
[uri]
(if (java.awt.Desktop/isDesktopSupported)
(let [desktop (java.awt.Desktop/getDesktop)]
(.browse desktop (java.net.URI. uri)))
(let [rt (java.lang.Runtime/getRuntime)]
(.exec rt (str "xdg-open " uri)))))
in case it's useful to anyone.
on windows invoke "cmd /k start http://www.example.com"
Infact you can always invoke "default" programs using the start command.
For ex start abc.mp3 will invoke the default mp3 player and load the requested mp3 file.
JavaFX bundles a cross-platform solution inside its StandaloneHostService that is independent of AWT, which is somehow similar to krzysiek.ste's answer.
I rewrote it to include some xdg-open alternatives (which are actually used by xdg-open by the way).
private static final String[][] commands = new String[][]{
{"xdg-open", "$1"},
{"gio", "open", "$1"},
{"gvfs-open", "$1"},
{"gnome-open", "$1"}, // Gnome
{"mate-open", "$1"}, // Mate
{"exo-open", "$1"}, // Xfce
{"enlightenment_open", "$1"}, // Enlightenment
{"gdbus", "call", "--session", "--dest", "org.freedesktop.portal.Desktop",
"--object-path", "/org/freedesktop/portal/desktop",
"--method", "org.freedesktop.portal.OpenURI.OpenURI",
"", "$1", "{}"}, // Flatpak
{"open", "$1"}, // Mac OS fallback
{"rundll32", "url.dll,FileProtocolHandler", "$1"}, // Windows fallback
};
Here is the final Java snippet, avoiding string concatenation and escape character issues.
public static void showDocument(final String uri) {
String osName = System.getProperty("os.name");
try {
if (osName.startsWith("Mac OS")) {
Runtime.getRuntime().exec(new String[]{"open", uri});
} else if (osName.startsWith("Windows")) {
Runtime.getRuntime().exec(new String[]{"rundll32", "url.dll,FileProtocolHandler", uri});
} else { //assume Unix or Linux
new Thread(() -> {
try {
for (String[] browser : commands) {
try {
String[] command = new String[browser.length];
for (int i = 0; i < browser.length; i++)
if (browser[i].equals("$1"))
command[i] = uri;
else
command[i] = browser[i];
if (Runtime.getRuntime().exec(command).waitFor() == 0)
return;
} catch (IOException ignored) {
}
}
String browsers = System.getenv("BROWSER") == null ? "x-www-browser:firefox:iceweasel:seamonkey:mozilla:" +
"epiphany:konqueror:chromium:chromium-browser:google-chrome:" +
"www-browser:links2:elinks:links:lynx:w3m" : System.getenv("BROWSER");
for (String browser : browsers.split(":")) {
try {
Runtime.getRuntime().exec(new String[]{browser, uri});
return;
} catch (IOException ignored) {
}
}
} catch (Exception ignored) {
}
}).start();
}
} catch (Exception e) {
// should not happen
// dump stack for debug purpose
e.printStackTrace();
}
}
There is also
BrowserUtil.browse(uri);
(source code) that seems to be a more compatible with some more exotic setups. I recently had a client where Desktop.getDesktop().browse(uri) was failing in Fedora Linux, but BrowserUtil.browse(uri) worked.
I also believe this is now the preferred way by JetBrains to open a browser (for example, see this thread)
As I had this same problem and found no decent solution for our case so I ported the https://www.npmjs.com/package/open npm package to Java https://github.com/vaadin/open and released it into Maven central. Can be used as
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>open</artifactId>
<version>8.4.0.2</version>
</dependency>
Open.open("https://stackoverflow.com/")
or for a specific browser
Open.open("https://stackoverflow.com/", App.FIREFOX);