I get the following exception when trying to create a file on windows 7 using Java. An example of a path is "C:/g-ecx/images-amazon/com/images/G/01/gno/images/orangeBlue/navPackedSprites-US-22.V183711641.png". If I hard code in a path it does work however. I've been banging my head for two hours, can anyone help.
mkdir fails but doesn't through an exception, create file throws the exception.
java.io.IOException: The system cannot find the path specified
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:883)
at org.willmanning.mtt.html.processingbehavior.ImageProcessingBehavior.processImage(ImageProcessingBehavior.java:125)
at org.willmanning.mtt.html.processingbehavior.ImageProcessingBehavior.loadImages(ImageProcessingBehavior.java:99)
at org.willmanning.mtt.html.processingbehavior.ImageProcessingBehavior.processNodes(ImageProcessingBehavior.java:66)
at org.willmanning.mtt.html.processingbehavior.ImageProcessingBehavior.processRootNode(ImageProcessingBehavior.java:34)
at org.willmanning.mtt.html.ParsingFacade.processURL(ParsingFacade.java:38)
at org.willmanning.mtt.App.main(App.java:45)
/**
*
* #param image
* #param url
*/
public void processImage(BufferedImage image, URL url) {
StringBuilder path = new StringBuilder();
path.append("C:/Users/will/Documents/");
path.append(url.getHost().replace('.', '/'));
path.append(url.getFile());
path.replace(path.lastIndexOf("."), path.length(), ".txt");
File file = new File(path.toString());
boolean mkdir = file.mkdir();
boolean isNew = false;
try {
isNew = file.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
/*
* only create the file if it doesn't exist
*/
if (isNew) {
try {
ImageIO.write(image, "jpg", file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Try using
boolean mkdir = file.mkdirs();
instead of
boolean mkdir = file.mkdir();
mkdirs() creates the whole parent path/directories if needed:
Related
I have a single .tar file with many folders and subfolders in it. Inside these many folders there are .7z files among other files. I'd like to search through these folders/subfolder and locate .7z files, (assign them to an array?) and extract them to their respective location.
I'm using Apache Commons:
1) org.apache.commons.compress.archivers.sevenz
Provides classes for reading and writing archives using the 7z format.
2) org.apache.commons.compress.archivers.tar
Provides stream classes for reading and writing archives using the TAR format.
step I wanna extract the .tar file
step I wanna go through the extracted .tar file folder and its subfolders recursively and locate .7z files.
In the 3. step I wanna feed the array the array of .7z files I found and extract them 1 by 1 to their respective locations.
I'm having problems in the 3. step with array call/assignment :/ Could you please help? Thank you very much :)
/**
* uncompresses .tar file
* #param in
* #param out
* #throws IOException
*/
public static void decompressTar(String in, File out) throws IOException {
try (TarArchiveInputStream tin = new TarArchiveInputStream(new FileInputStream(in))){
TarArchiveEntry entry;
while ((entry = tin.getNextTarEntry()) != null) {
if (entry.isDirectory()) {
continue;
}
File curfile = new File(out, entry.getName());
File parent = curfile.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
IOUtils.copy(tin, new FileOutputStream(curfile));
}
}
}
/**
* uncompresses .7z file
* #param in
* #param destination
* #throws IOException
*/
public static void decompressSevenz(String in, File destination) throws IOException {
//#SuppressWarnings("resource")
SevenZFile sevenZFile = new SevenZFile(new File(in));
SevenZArchiveEntry entry;
while ((entry = sevenZFile.getNextEntry()) != null){
if (entry.isDirectory()){
continue;
}
File curfile = new File(destination, entry.getName());
File parent = curfile.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
FileOutputStream out = new FileOutputStream(curfile);
byte[] content = new byte[(int) entry.getSize()];
sevenZFile.read(content, 0, content.length);
out.write(content);
out.close();
}
sevenZFile.close();
}
public void run()
{
//1) uncompress .tar
try {
JThreadTar.decompressTar(RECURSIVE_DIRECTORY_PATH, new File(RECURSIVE_DIRECTORY));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//2) go through the extracted .tar file directory and look for .7z (recursively?)
File[] files = new File(RECURSIVE_DIRECTORY).listFiles();
for (File file : files) {
if (file.isDirectory()) {
File[] matches = file.listFiles(new FilenameFilter()
{
public boolean accept(File dir, String name)
{
return name.endsWith(".7z");
}
});
for (File element: matches) {
System.out.println(element);
}
}
else {
continue;
}
}
//3) Feed the array above to decompressSevenz method
for (int i = 0; i < matches.length; i++)
{
if (matches[i].isFile())
{
try {
JThreadTar.decompressSevenz(matches[i].toString(), new File(RECURSIVE_DIRECTORY));
}
catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
}
My problem is: I can't refer to []matches in step 3. I'm not using this correctly. I just want to create an array []matches for .7z file matches. Every time a .7z is found, I'd like to add it to this array. and in the 3. step I wanna extract each .7z to its relative location.
I came a bit further:
//1) uncompress .tar
try {
JThreadTar.decompressTar(RECURSIVE_DIRECTORY_PATH, new File(RECURSIVE_DIRECTORY));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//2) go through the extracted .tar file directory and look for .7z (recursively?)
File dir = new File(RECURSIVE_DIRECTORY);
File[] dirFiles = dir.listFiles();
ArrayList<File> matches2 = new ArrayList<File>();
for (File file : dirFiles) {
if (file.isDirectory()) {
File[] matches = dir.listFiles(new FilenameFilter()
{
public boolean accept(File dir, String name)
{
return name.endsWith(".7z");
}
});
matches2.addAll(Arrays.asList(matches));
}
else if (file.isFile()) {
if (file.getName().endsWith(".7z")){
matches2.add(file);
};
}
};
//3) Feed the arraylist above to decompressSevenz method
for (int counter = 0; counter < matches2.size(); counter++) {
if (matches2.get(counter).isFile())
{
try {
JThreadTar.decompressSevenz(matches2.get(counter).toString(), new File(RECURSIVE_DIRECTORY));
}
catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
}
Here is after the final form of step 2 and step 3 from #Joop Eggen
Path topDir = Paths.get(RECURSIVE_DIRECTORY);
try {
Files.walk(topDir)
.filter(path -> path.getFileName().toString().endsWith(".7z"))
.forEach(path -> {
try {
JThreadTar.decompressSevenz(path.toString(), topDir.toFile());
} catch (IOException e2) {
e2.printStackTrace();
}
});
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
step recursively:
Path toptopDir = Paths.get(RECURSIVE_DIRECTORY_PATH);
try {
Files.walk(toptopDir)
.filter(path -> path.getFileName().toString().endsWith(".tar"))
.forEach(path -> {
try {
JThreadTar.decompressTar(RECURSIVE_DIRECTORY_PATH, new File(RECURSIVE_DIRECTORY));
} catch (IOException e2) {
e2.printStackTrace();
}
});
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
I took the opportunity to use the newer Path and Files. Files.listFiles() may return null. And the usage of Arrays.asList and such will cause heavy data.
All that would be simplified to:
Path topDir = Paths.get(RECURSIVE_DIRECTORY);
Files.walk(topDir)
.filter(path -> path.getFileName().toString().endsWith(".7z"))
.forEach(path -> {
try {
JThreadTar.decompressSevenz(path.toString(), topDir.toFile());
} catch (IOException e2) {
e2.printStackTrace();
}
});
Everyone keeps saying how simple it is to move a file from point a to point b using fileutils, but I'm having lots of trouble moving a file :(
I have a /temp/ folder in the directory wherever the .jar is located, in this temp folder I have a .txt file I want to move up a directory (so basically next to the .jar file) but I cant seem to do it?
Here's some code, but I know its not even close:
public void replaceFile() {
String absolutePath = getPath();
Path from = Paths.get(absolutePath + "\\temp\\test.txt");
Path to = Paths.get(absolutePath + "\\test.txt");
try {
FileUtils.moveFile(FileUtils.getFile(from.toAbsolutePath().toString()), FileUtils.getFile(to.toAbsolutePath().toString()));
JOptionPane.showMessageDialog(null, "test");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getPath() {
File jarDir = new File(ClassLoader.getSystemClassLoader().getResource(".").getPath());
//JOptionPane.showMessageDialog(null, jarDir.getAbsolutePath());
return jarDir.getAbsolutePath();
}
Any help is appreciated :\
Why don't use this Java API for Moving a File or Directory
Files.move(from, to, StandardCopyOption.REPLACE_EXISTING);
UPDATE
Looking at your source code I suggest the following implementation:
Path from = Paths.get(absolutePath, "/temp/test.txt");
Path to = Paths.get(absolutePath, "/test.txt");
try {
Files.move(from, to, StandardCopyOption.REPLACE_EXISTING);
JOptionPane.showMessageDialog(null, "test");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ok i managed to do it, apparently the getPath() method returned some funny path and it failed there, so heres a code that works
public void downloadJar() {
String absolutePath = getPath();
String from = absolutePath + "\\temp\\test.txt";
String to = absolutePath + "\\test.txt";
File fileTo = new File(to);
File fileFrom = new File(from);
try {
FileUtils.moveFile(fileFrom, fileTo);
JOptionPane.showMessageDialog(null, "test");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
JOptionPane.showMessageDialog(null, "io exce");
}
}
public String getPath() {
return System.getProperty("user.dir");
}
thanks everyone
I've made applet, Here's files from its jar.
In my classes I've call ffmpeg.exe, and I have all privileges like self-signed applet and make call via Access Controller. So I've getting error in program, It's can't be find *my ffmpeg lib*.
This should be very easy Q: where should I place my ffmpeg.exe file ?
And I've get exception as:
Cannot run program "ffmpeg": CreateProcess error=2, ?? ??? ??? ????? ????
The code are following as:
public class DtpVideoApplet extends Applet
{
public String startRecording() throws IOException
{
try
{
return(String) AccessController.doPrivileged(new PrivilegedAction<String>()
{
public String run()
{
try
{
Runtime.getRuntime()
.exec("ffmpeg -y -f dshow -i video=\"screen-capture-recorder\" output.flv");
return "Entered";
}
catch (Exception e)
{
// TODO Auto-generated catch block
return e.getMessage();
}
}
});
}
catch (Exception e)
{
return e.getMessage();
}
}
}
I never run an .exe from an applet, however I'm load some .dlls from an applet resource, to do this first I copy my applet resources to temp path and then I load it from this path. The dlls are located inside the jar how is showed below:
loadLib method copies .dlls to disc and then load it, this method receive as parameters the directory and the name of the file (in my case the method call is loadLib("/sun/security/mscapi/","sunmscapi_x32.dll"); )
public static void loadLib(String libraryPath, String libraryName) throws IOException, InterruptedException{
System.out.println(libraryPath + "---------------------");
URL inputStreamLibURL = AddSunMSCAPIProvider.class.getResource(libraryPath);
if(inputStreamLibURL==null){
throw new IOException("Resource not found: " + libraryPath);
}
String tempPath = System.getProperty("java.io.tmpdir", NOT_FOUND);
if(tempPath.equals(NOT_FOUND)){
throw new IOException("Temporary File not found");
}
File tempDir = new File(tempPath);
//first try to overwrite the default file
File defaultFile = new File(tempPath, libraryName);
boolean useDefaultFile = false;
if(defaultFile.exists()){
try{
useDefaultFile = defaultFile.delete();
//return false if the library cannot be deleted (locked)
}catch(Exception e){
e.printStackTrace();
useDefaultFile = false;
}
}else{
useDefaultFile = true;
}
File tempFile;
if(useDefaultFile){
tempFile = defaultFile;
}else{
tempFile = File.createTempFile(libraryName, "", tempDir);
}
copy(inputStreamLibURL.openStream() ,tempFile, 0);
Runtime.getRuntime().load(tempFile.getAbsolutePath());
}
/**
* File copy
* #param src
* #param dest
* #param bufferSize
* #throws IOException
*/
private static void copy(InputStream src, File dest, int bufferSize) throws IOException{
if(bufferSize<=0){
bufferSize = 2000; //default bytebuffer
}
InputStream is = src;
OutputStream os = new BufferedOutputStream(new FileOutputStream(dest));
byte[] buffer = new byte[bufferSize];
int c;
while((c = is.read(buffer))!= -1){
os.write(buffer, 0, c);
}
is.close();
os.close();
return;
}
Of course in order to do this operations, the applet must be correct signed and necessary MANIFEST permissions added.
Hope this helps,
Trying to create and write to a file, but i get a FileNotFoundException every time, here is the method i am using:
public void saveFileAsPRN(Context context){
byte[] dataFile = getPrintableFileData();
String filename = "TestPrn.prn";
// instantiate a file object using the path
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), filename);
Log.e(TAG, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString());
//determine if the media is mounted with read & write access
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
Log.e(TAG, "media mounted"); //good
}else{
Log.e(TAG, "media NOT mounted"); //bad
}
//create directory if it does not exist
//the default Download directory should always exist
if (!file.mkdirs()) {
Log.e(TAG, "Directory not created");
}
// determine if the file exists, create it if it does not
if(!file.exists()){
try {
Log.e(TAG, "File does not exist, creating..");
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
Log.e(TAG, "File Exists");
}
//this makes the blank file visible in the file browser
MediaScannerConnection.scanFile(context, new String[]{Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/" + filename}, null, null);
//create output stream - send data; saving to file
OutputStream out = null;
try {
FileOutputStream fos = null;
fos = new FileOutputStream(file); // <---- CRASHES HERE; FileNotFoundException
out = new BufferedOutputStream(fos);
out.write(dataFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
A FileNotFoundException is raised on the following line:
fos = new FileOutputStream(file); // <---- CRASHES HERE;
The directory Exists, and a blank file is created in the target directory (visible by browsing target folder on PC).
Calling the method canWrite() on the File object returns true - i have write access.
The manifest contains: android.permission.WRITE_EXTERNAL_STORAGE"
So i'm out of ideas, i see several people have similar issues, but i cant find an answer.
Commenting out the following code fixed the issue:
//create directory if it does not exist
//the default Download directory should always exist
if (!file.mkdirs()) {
Log.e(TAG, "Directory not created");
}
that code does create a blank file, you can see it contained in the folder,
BUT - it's very misleading; you can't do anything with this file, i tried transferring it from my device to my PC and i couldn't, i also cannot open it. and you cannot open a stream to it in code.
Try this may helps you.
Replace this line
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), filename);
With
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(), filename);
I have the problem, that I create a new file in a Java program, but I always get an exception, that the new created file is not local, when I try to open it on the eclipse project explorer view.
The code where I create it is as follows:
IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
IProject project = workspaceRoot.getProject(projectName);
FileUtil myFile = new FileUtil();
if (!project.getFile(FILE_NAME).exists()) {
IFile newFile = project.getFile("conf.txt");
FileInputStream fileStream = null;
try {
String temp = project + "/conf.txt";
temp = temp.substring(2);
fileStream = new FileInputStream(temp);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
newFile.create(fileStream, false, null);
} catch (CoreException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// create closes the file stream, so no worries.
try {
myFile.writeTextFile(FILE_NAME, "Seconds", output);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
FileUtil is a class which only implements the methods write and read for the file.
The Exception I get when I try to open it begins with:
org.eclipse.core.internal.resources.ResourceException: Resource '/ProjectE1/conf.txt' is not local.
at org.eclipse.core.internal.resources.Resource.checkLocal(Resource.java:353)
at org.eclipse.core.internal.resources.File.getContentDescription(File.java:264)
at org.eclipse.core.internal.propertytester.FilePropertyTester.testContentType(FilePropertyTester.java:108)
I somehow have to get a relative path during the runtime. Because I am opening a new instance of eclipse in the program, where I can see the Project in the Project Explorer but can't open the conf.txt file because it is not local.
It looks like your resource is an absolute path to /ProjectE1/conf.txt, I'm confused why you are not using java.io.
This will help you understand relative paths, I think this may be where you are wanting to put your conf file.
File file = new File("conf.txt");
if(!file.createNewFile()){
//err
}
System.out.println(file.getAbsolutePath());
I had similar issue. This is how I fixed.
First created file in local file system (using java.io)
Did project refresh
Reload the file
File file = new File(project.getWorkspace().getRoot().getLocation() + project.getFullPath().toString() + "/relative_path_of_my_file");
file.createNewFile();
project.refreshLocal(IProject.DEPTH_INFINITE, null);
keywordFile = project.getFile("/relative_path_of_my_file");