Java下转换路径
2020-02-26 11:36 tangxiaosheng 阅读(700) 评论(0) 编辑 收藏 举报是在windows上工作,参考https://my.oschina.net/redraiment/blog/1936368,开头尝试jni这个jar包,分别下载了
jnr-posix-3.0.54.jar,jnr-ffi-2.1.12.jar,jnr-constants-0.9.15.jar
发现在windows上不工作,于是参考https://stackoverflow.com/questions/840190/changing-the-current-working-directory-in-java/840253#840253,用了一些方案,发现不行,最后采用jna才解决。
我加入的代码是:
import com.sun.jna.Library; import com.sun.jna.Native; import com.sun.jna.Platform; private static interface MyKernel32 extends Library { public MyKernel32 INSTANCE = (MyKernel32) Native.loadLibrary("Kernel32", MyKernel32.class); /** BOOL SetCurrentDirectory( LPCTSTR lpPathName ); */ int SetCurrentDirectoryW(char[] pathName); } private void fileTagProjectMenuItemActionPerformed(java.awt.event.ActionEvent evt) { Runtime rn = Runtime.getRuntime(); Process p = null; String curDir = System.getProperty("user.dir"); String targetDir = curDir + "\\SourceInstrument\\"; try { addPrevillege(); // POSIX posix = POSIXFactory.getPOSIX(new PosixHandler(), true); // posix.chdir(targetDir); MyKernel32.INSTANCE.SetCurrentDirectoryW(targetDir.toCharArray()); String cmd1 = String.format("cmd /c cd %s && sci.exe", targetDir); // String cmd1 = targetDir + "sci.exe"; //cannot do so p = rn.exec(cmd1); p.waitFor(); MyKernel32.INSTANCE.SetCurrentDirectoryW(curDir.toCharArray()); // posix.chdir(curDir); // posix.exec("cmd /c start " + targetDir + "/Sci.exe"); } catch (Exception e) { Logger.getLogger("Exec").warning(targetDir ); } }
这样才能work。
关于jna学习资料,https://blog.csdn.net/gwd1154978352/article/details/55097376 这里面介绍的不错。