I have a .scala file inside a JAR, how do i open from my code that isn't part of the jar?
For some additional precisions the jar file does not on classpath.
Here an example of my code. It works partially, the file on the jar is open but for that i create it from the folder "lib'.
Have you another idea for evitate the creation of the file on the folder?
Thanks !
protected Object openDialogBox(Control cellEditorWindow, Object value, String jarFileName)
throws CoreException, IOException {
IWorkspaceRoot myWorkspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
IProject myProject = myWorkspaceRoot.getProject(ActiveProject.getNameProject());
String fileProgramName = (String) value;
InputStream stream;
final boolean readOnly = (jarFileName != null);
if (myProject.exists() && myProject.isOpen()) {
IFolder sourceFolder = myProject.getFolder( (jarFileName != null) ? "lib" : "src" );
if (sourceFolder.exists()) {
final IFile programFile = sourceFolder.getFile(fileProgramName);
if ( jarFileName != null ) {
programFile.delete(true, new NullProgressMonitor());
stream = JarUtil.getProgramFromJar(jarFileName, fileProgramName);
}
else {
stream = createContentStream(myProject.getName(), programFile.getName().replace(".scala", ""));
}
if (!programFile.exists()) {
// create the file
programFile.create(stream, true, new NullProgressMonitor());
}
programFile.refreshLocal(IResource.DEPTH_ZERO, null);
stream.close();
cellEditorWindow.getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
IWorkbenchPage page = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage();
try {
ResourceAttributes myAttributes = programFile.getResourceAttributes();
if (myAttributes == null) {
myAttributes = new ResourceAttributes();
}
myAttributes.setReadOnly(readOnly);
try {
programFile.setResourceAttributes(myAttributes);
} catch (CoreException e) {
e.printStackTrace();
}
IDE.openEditor(page, programFile, true);
} catch (PartInitException e) {
}
}
});
return value;
}
return null;
}
return null;
}
Related
I am new for android, Im downloading image from URL and set in listView. Its working some mobile and not creating file/directory in some mobile.
Its throw error like:
java.io.FileNotFoundException: /storage/emulated/0/.tam/veg.png: open failed: ENOENT (No such file or directory)
I don't know why its throw error like this some mobile. I want to create directory all type of mobile. Please anyone help me.
Here my code:
public class ImageStorage {
public static String saveToSdCard(Bitmap bitmap, String filename) {
String stored = null;
File sdcard = Environment.getExternalStorageDirectory();
File folder = new File(sdcard.getAbsoluteFile(), ".tam");//the dot makes this directory hidden to the user
folder.mkdir();
File file = new File(folder.getAbsoluteFile(), filename) ;
if (file.exists())
return stored ;
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
stored = "success";
} catch (Exception e) {
e.printStackTrace();
}
return stored;
}
public static File getImage(String imagename) {
File mediaImage = null;
try {
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
File myDir = new File(root);
if (!myDir.exists())
return null;
mediaImage = new File(myDir.getPath() + "/.tam/"+imagename);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mediaImage;
}
public static File checkifImageExists(String imagename) {
File file = ImageStorage.getImage("/" + imagename);
if (file.exists()) {
return file;
} else {
return null;
}
}
public static String getImageName(String value){
String getName[] = value.split("/");
return getName[4];
}
}
Below path not in all mobile:
/storage/emulated/0/
Thanks in advance!!
Maybe u should check if there's external storage in the mobile before u use this path
public String getDir(Context context) {
String checkPath = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
|| !Environment.isExternalStorageRemovable()) {
checkPath = Environment.getExternalStorageDirectory().getPath();
} else {
checkPath = context.getCacheDir().getPath();
}
return checkPath;
}
I use make directory in
IFileStore targetfileParent =
targetfileLocation.getParent().mkdir(EFS.SHALLOW, new
SubProgressMonitor(monitor, 0));
But I test it with
if(!targetfileLocation.getParent().fetchInfo().exists()){ }
It returns true that means it cannot found the parent folder, which created by targetfileLocation.getParent().mkdir. Whereas, i could find the folder is successfully created during debugging.
void processContainer(IContainer container,IProject targetProject,IProgressMonitor monitor) {
try {
IResource[] members = container.members();
for (IResource member : members)
{
if (member instanceof IContainer)
{
processContainer((IContainer)member,targetProject,monitor);
}
else if (member instanceof IFile)
{
IFile memberfile = (IFile)member;
IPath relativefilePath = memberfile.getProjectRelativePath();
String fileName = relativefilePath.toOSString();
if(fileName.endsWith(".java.color")||fileName.endsWith(".color")){
continue;
}
IResource resouce = targetProject.findMember(relativefilePath);
if(resouce==null){
IFile targetfile = targetProject.getFile(relativefilePath);
IFileStore sourcefileLocation = EFS.getLocalFileSystem().getStore(memberfile.getFullPath());
if(memberfile.exists()){
if(!targetfile.exists()){
IFileStore targetfileLocation = EFS.getLocalFileSystem().getStore(workspaceRoot.append(targetProject.getFullPath()).append(relativefilePath));
if(!targetfileLocation.getParent().fetchInfo().exists()){
IFileStore targetfileParent = targetfileLocation.getParent().mkdir(EFS.SHALLOW, new SubProgressMonitor(monitor, 0));
if(!targetfileLocation.getParent().fetchInfo().exists()){
System.out.println("Not exist");
}
}
System.out.println("Copy to distance:"+targetProject.getFullPath().append(relativefilePath).toOSString());
memberfile.copy(targetProject.getFullPath().append(relativefilePath), EFS.SHALLOW, new SubProgressMonitor(monitor, 0));
}
}
}
}
} } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); }
}
I want to list all files in resources classpath ,I used the following code but get null exception in fList
String path = request.getSession().getServletContext().getRealPath("/resources/rules");
File directory = new File(path);
File[] fList = directory.listFiles();
for (File file : fList){
if (file.isFile()){
System.out.println(file.getName());
}
}
Here is a working example:
https://github.com/bleujin/aradon/blob/master/src/net/ion/nradon/helpers/ClassloaderResourceHelper.java#L30
public static Iterable<FileEntry> listFilesRelativeToClass(Class<?> clazz, String subdirectory) throws IOException {
ArrayList<FileEntry> list = new ArrayList<FileEntry>();
CodeSource src = clazz.getProtectionDomain().getCodeSource();
if (src == null) {
return list;
}
URL classpathEntry = src.getLocation();
try {
// Check if we're loaded from a folder
File file = new File(new File(classpathEntry.toURI()), subdirectory);
if (file.isDirectory()) {
return fileEntriesFor(file.listFiles());
}
} catch (URISyntaxException e) {
// Should never happen, because we know classpathentry is valid
throw new RuntimeException(e);
}
// We're not in a folder, so we must be in a jar or similar
subdirectory = subdirectory.replace(File.separatorChar, '/');
if (!subdirectory.endsWith("/")) {
subdirectory = subdirectory + "/";
}
ZipInputStream jarStream = new ZipInputStream(classpathEntry.openStream());
ZipEntry zipEntry;
while ((zipEntry = jarStream.getNextEntry()) != null) {
if (isChild(subdirectory, zipEntry.getName())) {
String basename = zipEntry.getName().substring(subdirectory.length());
int indexOfSlash = basename.indexOf('/');
if (indexOfSlash < 0 || indexOfSlash == basename.length() - 1) {
list.add(new FileEntry(basename));
}
}
}
return list;
}
private static boolean isChild(String parent, String name) {
return name.startsWith(parent);
}
public static Iterable<FileEntry> fileEntriesFor(File[] files) {
List<FileEntry> fileEntries = new ArrayList<FileEntry>(files.length);
for (File file : files) {
String filename = file.getName();
if (file.isDirectory()) {
filename += "/";
}
fileEntries.add(new FileEntry(filename));
}
return fileEntries;
}
}
How about this source code?
String[] resoures = srcDir.list( new java.io.FilenameFilter()
{
public boolean accept( File dir, String name )
{
String[] extensions = { ".png", ".jar", ".txt" };
String fileName = name.toLowerCase( Locale.getDefault() );
for ( int i = 0; i < extensions.length; i++ )
{
if ( fileName.endsWith( extensions[i] ) )
{
return true;
}
}
return false;
}
} );
Full source here:
http://code.openhub.net/file?fid=kpl9VrAT-CHXE496rmMP8Jbzo5U&cid=y9kXCqEmUoY&s=List%20all%20files%20in%20resoures%20directory%20in%20java%20project&pp=0&fl=Java&ff=1&projSelected=false&filterChecked,=true&mp,=1&mp=1&ml=1&me=1&md=1#L64
I have written a Java Classloader to load classes from a .jar file.
However when I load a Class I get a ClassNotFoundException. The .jar file is located in folder assets. Before the operation I copied the .jar file in another directory.
Why does it happen and how can I load class from jar file?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
try {
final File dexInternalStoragePath = new File(getDir("lib", Context.MODE_PRIVATE), SECONDARY_DEX_NAME);
(new PrepareDexTask()).execute(dexInternalStoragePath);
if (dexInternalStoragePath.exists()) {
final File optimizedDexOutputPath = getDir("outdex", Context.MODE_PRIVATE);
DexClassLoader cl = new DexClassLoader(dexInternalStoragePath.getAbsolutePath(),
optimizedDexOutputPath.getAbsolutePath(), null, getClassLoader());
try {
JarFile jarFile = new JarFile(dexInternalStoragePath.getAbsolutePath());
Enumeration<?> e = jarFile.entries();
URL[] urls = { new URL("jar:file:" + dexInternalStoragePath.getAbsolutePath() + "!/") };
URLClassLoader cl1 = URLClassLoader.newInstance(urls);
while (e.hasMoreElements()) {
JarEntry je = (JarEntry) e.nextElement();
if (je.isDirectory() || !je.getName().endsWith(".class")) {
continue;
}
String className = je.getName().substring(0, je.getName().length() - 6);
className = className.replace('/', '.');
if (className.equals("com.common.lvl.LibraryProvider")) {
LibraryInterface lib = (LibraryInterface) Class.forName(className, true, cl1).newInstance();
//Class<?> libProviderClazz = cl1.loadClass(className);
//LibraryInterface lib = (LibraryInterface) libProviderClazz.newInstance();
lib.CheckLVL(this, "hello");
}
}
// Class<?> libProviderClazz =
// cl.loadClass("com.common.lvl.LibraryProvider");
// LibraryInterface lib = (LibraryInterface)
// libProviderClazz.newInstance();
// lib.CheckLVL(this, "hello");
} catch (Exception ex) {
Logger.Instance().WriteLine(this, ex.getMessage());
}
}
} catch (Exception ex) {
}
}
private boolean prepareDex(File dexInternalStoragePath) {
BufferedInputStream bis = null;
OutputStream dexWriter = null;
try {
bis = new BufferedInputStream(getAssets().open(SECONDARY_DEX_NAME));
dexWriter = new BufferedOutputStream(new FileOutputStream(dexInternalStoragePath));
byte[] buf = new byte[BUF_SIZE];
int len;
while ((len = bis.read(buf, 0, BUF_SIZE)) > 0) {
dexWriter.write(buf, 0, len);
}
dexWriter.close();
bis.close();
return true;
} catch (IOException e) {
if (dexWriter != null) {
try {
dexWriter.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
if (bis != null) {
try {
bis.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return false;
}
}
private class PrepareDexTask extends AsyncTask<File, Void, Boolean> {
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
}
#Override
protected Boolean doInBackground(File... dexInternalStoragePaths) {
prepareDex(dexInternalStoragePaths[0]);
return null;
}
}
Add your jar file, like below
go to -> project properties in eclipse -> java build path -> Libraries -> Add External Jar, And browse and locate you jar file.
File content[] = new File("C:/FilesToGo/").listFiles();
for (int i = 0; i < content.length; i++){
String destiny = "C:/Kingdoms/"+content[i].getName();
File desc = new File(destiny);
try {
Files.copy(content[i].toPath(), desc.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
}
This is what I have. It copies everything just fine.
But among the contents there are some folders. The folders are copied but the folder's contents are not.
Would recommend using FileUtils in Apache Commons IO:
FileUtils.copyDirectory(new File("C:/FilesToGo/"),
new File("C:/Kingdoms/"));
Copies directories & contents.
Recursion. Here is a method the uses rescursion to delete a system of folders:
public void move(File file, File targetFile) {
if(file.isDirectory() && file.listFiles() != null) {
for(File file2 : file.listFiles()) {
move(file2, new File(targetFile.getPath() + "\\" + file.getName());
}
}
try {
Files.copy(file, targetFile.getPath() + "\\" + file.getName(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
}
Didn't test the code, but it should work. Basically, it digs down into the folders, telling it to move the item, if its a folder, go through all its children, and move them, etc.
Just to clarify what needs to be changed in Alex Coleman's answer, for the code to work. Here is the modified version of Alex's code that I tested and that works fine for me:
private void copyDirectoryContents(File source, File destination){
try {
String destinationPathString = destination.getPath() + "\\" + source.getName();
Path destinationPath = Paths.get(destinationPathString);
Files.copy(source.toPath(), destinationPath, StandardCopyOption.REPLACE_EXISTING);
}
catch (UnsupportedOperationException e) {
//UnsupportedOperationException
}
catch (DirectoryNotEmptyException e) {
//DirectoryNotEmptyException
}
catch (IOException e) {
//IOException
}
catch (SecurityException e) {
//SecurityException
}
if(source.isDirectory() && source.listFiles() != null){
for(File file : source.listFiles()) {
copyDirectoryContents(file, new File(destination.getPath() + "\\" + source.getName()));
}
}
}
The question is old by now, but I wanted to share my copy methods using java.nio.file.
Copying source directory: src into a container directory: dst.
"Directory" is just a helper class. In this example you can think of it as "Path" container.
We separate the directory structure from the file content.
It's explicit, and easy to imagine. (Also, it avoids some potential Exceptions thrown by the Files.copy() method if you instead copied all files in "one go")
public static void copy(Directory src, Directory dst, boolean replace) throws IOException {
if (src == null || dst == null) throw new IllegalArgumentException("...");
Path sourcePath = src.path();
Path targetPath = dst.path().resolve(sourcePath.getFileName());
copyStructure(sourcePath,targetPath);
copyContent(sourcePath,targetPath,replace);
}
I.e. we want to copy the folder "top" into the "dst" folder "container".
sourcePath = ...some/location/top
targetPath = ...another/location/container/top
copyStructure: Iterates through the source files. If the source file is a directory and the a target file with equivalent name does not exist, we create
the target folder. (So "copy" is not accurate. We "assure" structure)
private static void copyStructure(final Path source, final Path target) throws IOException {
if (source == null || target == null) throw new IllegalArgumentException("...");
final String tarString = target.toString();
final String srcString = source.toString();
Files.walk(source).forEach(new Consumer<Path>() {
#Override
public void accept(Path srcPath) {
if (Files.isDirectory(srcPath)) {
String subString = srcPath.toString().substring(srcString.length());
Path newFolder = Path.of(tarString,subString);
if (!Files.exists(newFolder)) {
try { Files.createDirectory(newFolder);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
});
}
Now that we know that a target directory structure exists, we iterate the source files again. But now we only copy the "content" (regular files). Choosing whether to replace existing content. copyContent:
private static void copyContent(final Path source, final Path target, boolean replace) throws IOException {
if (source == null || target == null) throw new IllegalArgumentException("...");
final String tarString = target.toString();
final String srcString = source.toString();
Files.walk(source).forEach(new Consumer<Path>() {
#Override
public void accept(Path srcPath) {
if (Files.isRegularFile(srcPath)) {
String subString = srcPath.toString().substring(srcString.length());
Path newFile = Path.of(tarString,subString);
if (!Files.exists(newFile)) {
try { Files.copy(srcPath,newFile);
} catch (IOException e) {
e.printStackTrace();
}
} else {
if (replace) {
try { Files.copy(srcPath,newFile,
StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
});
}