Creating folder in the local file system - java

I'm having the following code in my mapper [ Hadoop - Map Reduce ]
Im trying to create a folder in the shared path
protected void setup(Context context)
throws IOException,InterruptedException
{
fileName1 = ((FileSplit) context.getInputSplit()).getPath().getName().toString();
Directory = "\\\\DEV144\\MapperFile\\"+fileName1;
File directory1 = new File(Directory);
if (!directory1.exists())
{
boolean result = new File(Directory).mkdirs();
System.out.println(Directory);
if(result)
{
System.out.println("DIR created");
System.out.println(Directory);
}
}
mos = new MultipleOutputs(context);
above code is not creating the folder. But when i give something like this
Directory = "E:\\MapperFile\\"+fileName1;
File directory1 = new File(Directory);
And point the local system it is creating Folder and working fine
My question is why it is not able to create folder in the shared path ?
And what is wrong in my code

I had a similar problem and I start using jCIFS. I have to point out that this was used to access windows shared directory from a linux machine. For creating directory you can use:
String smbUrl = "smb://domain;username:password#server/share/myNewDirectory";
SmbFile smbFile = new SmbFile(smbURL);
try{
smbFile.mkdir();
}catch(SmbException e){...}
And don't forget to check if you have sufficient permissions for a java application.

Related

Random file from a folder inside JAR

I want to get a random image from a specific folder in Java. The code does already work inside the Eclipse IDE, but not in my runnable JAR. Since images inside the JAR file are not files, the code below results in a NullPointerException, but I'm not sure how to "translate" the code so that it will work in a runnable JAR.
final File dir = new File("images/");
File[] files = dir.listFiles();
Random rand = new Random();
File file = files[rand.nextInt(files.length)];
If the given path is invalid then listFiles() method reutrns null value. So you have to handle it if the path is invalid. Check below code:
final File dir = new File("images/");
File[] files = dir.listFiles();
Random rand = new Random();
File file = null;
if (files != null) {
file = files[rand.nextInt(files.length)];
}
If the jar is to contain the images then (assuming a maven or gradle project) they should be in the resources directory (or a subdirectory thereof). These images are then indeed no 'Files' but 'Resources' and should be loaded using getClass().getResource(String name) or getClass.getResourceAsStream(String name).
You could create a text file listing the resource paths of the images. This would allow you to simply read all lines from that file and access the resource via Class.getResource.
You could even create such a list automatically. The following works for my project type in eclipse; some minor adjustments may be needed for your IDE.
private static void writeResourceCatalog(Path resourcePath, Path targetFile) throws IOException {
URI uri = resourcePath.toUri();
try (BufferedWriter writer = Files.newBufferedWriter(targetFile, StandardCharsets.UTF_8)) {
Files.list(resourcePath.resolve("images")).filter(Files::isRegularFile).forEach(p -> {
try {
writer.append('/').append(uri.relativize(p.toUri()).toString()).append('\n');
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
}
writeResourceCatalog(Paths.get("src", "main", "resources"), Paths.get("src", "main", "resources", "catalog.txt"));
After building the jar with the new file included you could simply list all the files as
List<URL> urls = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(WriteTest.class.getResourceAsStream("/catalog.txt"), StandardCharsets.UTF_8))) {
String s;
while ((s = reader.readLine()) != null) {
urls.add(SomeType.class.getResource(s));
}
}
It seem like a path Problem, maybe will work if tried absolute path for image directory or set maon directory for java configuration

jcifs copyTo from one network to other network path not working

I'm using the Java CIFS Client Library but facing the problem and problem is copyTo function is not working.
I have one folder which contains files. I want to read these files to other network path.
String path1 = "//MACHINE-NAME/SHARE-FOLDER"
NtlmPasswordAuthentication auth = new
NtlmPasswordAuthentication(DOMAIN;USERNAME:PASSWORD)
SmbFile readFolder = new SmbFile("smb://MACHINE-NAME/SHARE-FOLDER/",auth)
This is working fine.
Then i have another network path and define like this and ShareFolder2 is have the read/write access to 'everyone' user.
String path2 = "//MACHINE-NAME/SHARE-FOLDER2"
NtlmPasswordAuthentication auth = new
NtlmPasswordAuthentication(DOMAIN;USERNAME:PASSWORD)
SmbFile destinationFolder = new SmbFile("smb://MACHINE-NAME/SHARE-FOLDER2/",auth)
ArrayList<SmbFile> readFiles = readFolder?.listFiles()
for(file in readFiles ){
file.copyTo(destinationFolder)
}
If you wanted to copy a file from one shared location to another shared location. You can this like this
ArrayList<SmbFile> readFiles = readFolder?.listFiles()
for(file in readFiles ){
String name = file.properties.getKey("name")
destinationFolder = new SmbFile(foldersInfo?.destinationFolder+"/"+name,auth)
destinationFolder.createNewFile()
file.copyTo(destinationFolder)
}
The file which you want to copy that file must be in the destination folder.
First we will create a file with same name in the destination folder then copy to that folder

Copy one file from a folder to another folder in java

I am trying to copy a file form a folder to another folder
i have tried what was suggested in other posts but i have not been successful
Copying files from one directory to another in Java
this has not worked for me
the file is C:/Users/win7/Desktop/G1_S215075820014_T111_N20738-A_D2015-01-26_P_H0.xml
the destination folder is C:/Users/win7/Desktop/destiny
this is the copy code
String origen = "C:/Users/win7/Desktop/G1_S215075820014"
+"_T111_N20738-A_D2015-01-26_P_H0.xml";
String destino = "C:/Users/win7/Desktop/destiny";
private void copiarArchivoACarpeta(String origen, String destino) throws IOException {
Path FROM = Paths.get(origen);
Path TO = Paths.get(destino);
CopyOption[] options =
new CopyOption[] {StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES };
java.nio.file.Files.copy(FROM, TO, options);
}
Try:
java.nio.file.Files.copy(FROM, TO.resolve(FROM.getFileName()),
StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
Because the second parameter must be a Path to a file that not yet exists.
Just like the docu sais:

Install the osgi bundle using the byte array instead of file location?

I am trying to install OSGi bundles. I am able to do it successfully. Right now what I am doing is, in our company we have some sort of storage where we are storing all the OSGi bundles jar. So I go and download those OSGi bundles jar into some local directory and then I try to install those bundles from the local location where it got downloaded from my storage repository.
And below method accepts only file location- So I provide my full local file path to this.
context.installBundle(localFilename)
Is there any way, I can install it using the byte[]. Basically I am trying to avoid downloading the jar file from my storage location to some local folder and then use that local location to install the bundles.
private static void callMethod() throws BundleException {
final IStorageServiceClient client = StorageServiceConsumerProvider.getStorageServiceClient(envType);
final StorageObjectIdentifier objIdentifierDir = new StorageObjectIdentifier(name, version, null);
final List<Map<String, String>> dirs = new ArrayList<Map<String, String>>();
client.listDirectory(objIdentifierDir, dirs);
final String filename = name + Constants.DASH + version + Constants.DOTJAR;
final String localFilename = basePath + File.separatorChar + filename;
// first of all, I am trying to delete the jar file from the local folder, if it is already there
new File(localFilename).delete();
final StorageObjectIdentifier objIdentifier = new StorageObjectIdentifier(name, version, filename);
// now I get the byte array of the jar file here.
final byte[] b = client.retrieveObject(objIdentifier);
// now I am writing that jar file to that local folder again using the byte array.
final FileOutputStream fos = new FileOutputStream(localFilename);
fos.write(b);
fos.close();
// now the jar file is there in that location, and now I am using the full path of the jar file to intall it.
BundleContext context = framework.getBundleContext();
List<Bundle> installedBundles = new LinkedList<Bundle>();
installedBundles.add(context.installBundle(localFilename));
for (Bundle bundle : installedBundles) {
bundle.start();
}
}
Is there any way to do this thing without copying the jar file from my storage location to my local folder and then use the full path to my local jar file and then install it?
Can anyone help me with this with a simple example basis on above code? Thanks for the help.
I didn't try it, but BundleContext#installBundle(String, InputStream) should be suitable for this. Using the mentioned method, your code would like this (local file creation has been removed):
private static void callMethod() throws BundleException {
final IStorageServiceClient client = StorageServiceConsumerProvider.getStorageServiceClient(envType);
final StorageObjectIdentifier objIdentifierDir = new StorageObjectIdentifier(name, version, null);
final List<Map<String, String>> dirs = new ArrayList<Map<String, String>>();
client.listDirectory(objIdentifierDir, dirs);
final String filename = name + Constants.DASH + version + Constants.DOTJAR;
final StorageObjectIdentifier objIdentifier = new StorageObjectIdentifier(name, version, filename);
// now I get the byte array of the jar file here.
final byte[] b = client.retrieveObject(objIdentifier);
// now the jar file is there in that location, and now I am using the full path of the jar file to intall it.
BundleContext context = framework.getBundleContext();
List<Bundle> installedBundles = new LinkedList<Bundle>();
installedBundles.add(context.installBundle(fileName, new ByteArrayInputStream(b)));
for (Bundle bundle : installedBundles) {
bundle.start();
}
}

Is it possible to create a NEW zip file using the java FileSystem?

I've successfully modified the contents of a (existing) zip file using the FileSystem provided by java 7, but when I tried to create a NEW zip file by this method it fails, with the error message that says: "zip END header not found", it is logical because of the way I'm doing it, first I create the file (Files.createFile) which is a completely empty file, and then I try to access to its file system , and since the file is empty its impossible to find any header inside the zip, my question is is there any way to create a new zip file completely empty using this method?; the hack that I've considered is adding an empty new ZipEntry to a the zip file and then using that new empty file to crate the file system based on it, but i really want to think that the guys of oracle implemented a better (easier) way to do this with nio and the filesystems...
this is my code (the error appears when creating the file system):
if (!zipLocation.toFile().exists()) {
if (creatingFile) {
Files.createFile(zipLocation);
}else {
return false;
}
} else if (zipLocation.toFile().exists() && !replacing) {
return false;
}
final FileSystem fs = FileSystems.newFileSystem(zipLocation, null);
.
.
.
zipLocation is a Path
creatingFile is a boolean
ANSWER:
in my particular case the answer given didn't work appropriately because of the spaces in the path, therefore i have to do it the way i didn't want to:
Files.createFile(zipLocation);
ZipOutputStream out = new ZipOutputStream(
new FileOutputStream(zipLocation.toFile()));
out.putNextEntry(new ZipEntry(""));
out.closeEntry();
out.close();
it does not mean that the given answer is wrong, it just didn't work for my particular case
As described in The Oracle Site:
public static void createZip(Path zipLocation, Path toBeAdded, String internalPath) throws Throwable {
Map<String, String> env = new HashMap<String, String>();
// check if file exists
env.put("create", String.valueOf(Files.notExists(zipLocation)));
// use a Zip filesystem URI
URI fileUri = zipLocation.toUri(); // here
URI zipUri = new URI("jar:" + fileUri.getScheme(), fileUri.getPath(), null);
System.out.println(zipUri);
// URI uri = URI.create("jar:file:"+zipLocation); // here creates the
// zip
// try with resource
try (FileSystem zipfs = FileSystems.newFileSystem(zipUri, env)) {
// Create internal path in the zipfs
Path internalTargetPath = zipfs.getPath(internalPath);
// Create parent directory
Files.createDirectories(internalTargetPath.getParent());
// copy a file into the zip file
Files.copy(toBeAdded, internalTargetPath, StandardCopyOption.REPLACE_EXISTING);
}
}
public static void main(String[] args) throws Throwable {
Path zipLocation = FileSystems.getDefault().getPath("a.zip").toAbsolutePath();
Path toBeAdded = FileSystems.getDefault().getPath("a.txt").toAbsolutePath();
createZip(zipLocation, toBeAdded, "aa/aa.txt");
}

Categories