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(); }
}
Related
I want to delete a images older than N days I do this :
File f = new File("/sdcard/Foto+");
File[] files1 = f.listFiles();
public void deleteFilesOlderThanNdays(File[] listFiles) {
long purgeTime = System.currentTimeMillis() - (Config.daysBackToDelete * 24 * 60 * 60 * 1000);
for (File listFile : listFiles) {
if (listFile.lastModified() < purgeTime) {
listFile.delete();
if(listFile.exists()){
try {
listFile.getCanonicalFile().delete();
} catch (IOException e) {
e.printStackTrace();
}
if(listFile.exists()){
getApplicationContext().deleteFile(listFile.getName());
}
}
}
}
}
And in this case when I try do this a images doesn't remove from this folder.
You need to delete file from MediaStore as well. Use the following method
deleteFileFromMediaStore(getContext().getContentResolver(), listFile);
Just call above method after deleting your image.
public static void deleteFileFromMediaStore(final ContentResolver contentResolver, final File file) {
String canonicalPath;
try {
canonicalPath = file.getCanonicalPath();
final Uri uri = MediaStore.Files.getContentUri("external");
final int result = contentResolver.delete(uri,
MediaStore.Files.FileColumns.DATA + "=?", new String[]{canonicalPath});
if (result == 0) {
final String absolutePath = file.getAbsolutePath();
if (!absolutePath.equals(canonicalPath)) {
contentResolver.delete(uri,
MediaStore.Files.FileColumns.DATA + "=?", new String[]{absolutePath});
}
}
} catch (IOException e) {
canonicalPath = file.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
}
}
After writing the text files into a directory, i am trying to delete the empty files written by the PrintWriter.
File.delete() function fails to delete the file. Below is the code for writing and deleting.
private static void writeFile(ArrayList<ArrayList<String>> listRowVal, String szOutputDir, ArrayList<String> listHeader){
PrintWriter pw = null;
try {
ArrayList<String> listCells = listRowVal.get(0);
int iCells = listCells.size();
for(int k=0; k<iCells; k++){
String language = listHeader.get(k);
String szFileName = "files_"+ language +".csv";
pw = new PrintWriter(new FileWriter(szOutputDir + File.separator + szFileName));
for(ArrayList<String> listNCRCellVal : listRowVal){
String szVal = listNCRCellVal.get(k);
if(szVal != null && szVal.trim().length() > 0){
pw.println(szVal);
}
pw.flush();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
if(pw != null){
pw.close();
pw = null;
}
//System.gc();
deleteEmptyFiles(szOutputDir);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private static void deleteEmptyFiles(String szDirPath) {
File file = new File(szDirPath);
if (file.isDirectory()) {
String[] files = file.list();
if (files.length > 0) {
for (String szFileName : files) {
File deleteFile = new File(szDirPath + File.separator + szFileName);
if (deleteFile.length() == 0) {
//deleteFile.setWritable(true, false);
boolean bdeleted = deleteFile.delete();
if(bdeleted){
System.out.println(deleteFile.getName() + " deleted.");
}
}
}
}
}
}
What is going wrong..??
You must close each PrintWriter, i.e. pw.close() must be on the end of "k" loop.
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.
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;
}
I'm trying to extract the files in an .iso file I have. There are no errors and the console prints out all the files inside. However, none of the files get extracted. Any help is greatly appreciated!
I was able to find this link but I can't seem to integrate it in to my project.
Link to code example
class DownloadWorker extends SwingWorker<String, Object> {
private String flocation;
private JLabel out;
public DownloadWorker(String location, JLabel fout)
{
this.flocation = location;
this.out = fout;
}
#Override
public String doInBackground() {
//download here
out.setText("Beginning download. This may take a few minutes.");
try {
//ProgressBar/Install
System.out.println("FILELOCATION:\n----------");
System.out.println(flocation);
String URL_LOCATION = "http://www.futureretrogaming.tk/gamefiles/ProfessorPhys.iso";
String LOCAL_FILE = (flocation + "\\ProfessorPhys\\");
File localfile = new File(LOCAL_FILE);
if (localfile.exists()) {
System.out.println("Directory exists!");
}
else {
System.out.println("Directory doesn't exist! Creating...");
localfile.mkdir();
if (localfile.exists())
System.out.println("Directory created!");
}
System.out.println("LOCALFILE:\n-------");
System.out.println(LOCAL_FILE);
URL website = new URL(URL_LOCATION);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(LOCAL_FILE+"\\ProfessorPhys.iso\\");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
System.out.println("--------\nDone Downloading\n---------");
RandomAccessFile randomAccessFile = null;
ISevenZipInArchive inArchive = null;
try {
randomAccessFile = new RandomAccessFile(localfile +"\\ProfessorPhys.iso\\", "r");
inArchive = SevenZip.openInArchive(null, // autodetect archive type
new RandomAccessFileInStream(randomAccessFile));
// Getting simple interface of the archive inArchive
ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();
System.out.println(" Hash | Size | Filename");
System.out.println("----------+------------+---------");
for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
final int[] hash = new int[] { 0 };
if (!item.isFolder()) {
ExtractOperationResult result;
final long[] sizeArray = new long[1];
result = item.extractSlow(new ISequentialOutStream() {
public int write(byte[] data) throws SevenZipException {
hash[0] ^= Arrays.hashCode(data); // Consume data
sizeArray[0] += data.length;
return data.length; // Return amount of consumed data
}
});
if (result == ExtractOperationResult.OK) {
System.out.println(String.format("%9X | %10s | %s", //
hash[0], sizeArray[0], item.getPath()));
} else {
System.err.println("Error extracting item: " + result);
}
}
}
} catch (Exception e) {
System.err.println("Error occurs: " + e);
System.exit(1);
} finally {
if (inArchive != null) {
try {
inArchive.close();
} catch (SevenZipException e) {
System.err.println("Error closing archive: " + e);
}
}
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
System.err.println("Error closing file: " + e);
}
}
}
} catch (Exception e) {
System.out.println(e);
}
return "done";
}
#Override
protected void done() {
//done
out.setText(out.getText() + "\n Operation Done");
}
}
Code I'm trying to implement:
public class ExtractorUtil {
private static Logger logger = Logger.getLogger(ExtractorUtil.class.getCanonicalName());
public static void extract(File file, String extractPath) throws Exception {
ISevenZipInArchive inArchive = null;
RandomAccessFile randomAccessFile = null;
randomAccessFile = new RandomAccessFile(file, "r");
inArchive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile));
inArchive.extract(null, false, new MyExtractCallback(inArchive, extractPath));
if (inArchive != null) {
inArchive.close();
}
if (randomAccessFile != null) {
randomAccessFile.close();
}
}
public static class MyExtractCallback implements IArchiveExtractCallback {
private final ISevenZipInArchive inArchive;
private final String extractPath;
public MyExtractCallback(ISevenZipInArchive inArchive, String extractPath) {
this.inArchive = inArchive;
this.extractPath = extractPath;
}
#Override
public ISequentialOutStream getStream(final int index, ExtractAskMode extractAskMode) throws SevenZipException {
return new ISequentialOutStream() {
#Override
public int write(byte[] data) throws SevenZipException {
String filePath = inArchive.getStringProperty(index, PropID.PATH);
FileOutputStream fos = null;
try {
File dir = new File(extractPath);
File path = new File(extractPath + filePath);
if (!dir.exists()) {
dir.mkdirs();
}
if (!path.exists()) {
path.createNewFile();
}
fos = new FileOutputStream(path, true);
fos.write(data);
} catch (IOException e) {
logger.severe(e.getLocalizedMessage());
} finally {
try {
if (fos != null) {
fos.flush();
fos.close();
}
} catch (IOException e) {
logger.severe(e.getLocalizedMessage());
}
}
return data.length;
}
};
}