tilde (~) in java File path - java

Any idea why this works fine even on a Windows environment ?
Can you point me to some docs which explains why this works ?
I tried to look for it with no results.
package com.my.example;
import org.junit.Test;
import java.io.File;
public class TestPathCreation
{
#Test
public void testPathCreation() throws Exception {
final String path = "~/.my/dir";
System.out.println(path);
File f = new File(path);
System.out.println(f.mkdirs()); // true
}
}

Related

Copying file using Apache Commons FileUtils

On the first run, I want to copy the given File to a new location with a new file name.
Every subsequent run should overwrite the same destination file created during first run.
During first run, the destination file does not exist. Only the directory exists.
I wrote the following program:
package myTest;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import org.apache.commons.io.FileUtils;
public class FileCopy {
public static void main(String[] args) {
TestFileCopy fileCopy = new TestFileCopy();
File sourceFile = new File("myFile.txt");
fileCopy.saveFile(sourceFile);
File newSourceFile = new File("myFile_Another.txt");
fileCopy.saveFile(newSourceFile);
}
}
class TestFileCopy {
private static final String DEST_FILE_PATH = "someDir/";
private static final String DEST_FILE_NAME = "myFileCopied.txt";
public void saveFile(File sourceFile) {
URL destFileUrl = getClass().getClassLoader().getResource(DEST_FILE_PATH
+ DEST_FILE_NAME);
try {
File destFile = Paths.get(destFileUrl.toURI()).toFile();
FileUtils.copyFile(sourceFile, destFile);
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
}
}
However, this throws null pointer exception on the following line:
File destFile = Paths.get(destFileUrl.toURI()).toFile();
What am I missing?
Directory someDir is directly under my project's root directory in eclipse.
Both source files myFile.txt and myFile_Another.txt exists directly under my project's root directory in eclipse.
I used this and it works as I am expecting:
public void saveFile1(File sourceFile) throws IOException {
Path from = sourceFile.toPath();
Path to = Paths.get(DEST_FILE_PATH + DEST_FILE_NAME);
Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING);
}
Using Java nio.

Copy all the files from a directory to another

i'm trying to copy all the files inside a directory to another(but i want it to not copy the folders). I'm trying to use Files.copy but i'm getting this error:
Exception in thread "main" java.nio.file.FileAlreadyExistsException:
Here's my actual code:
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Exercici1 {
public static void copiarArchivos(String pathSource,String pathOutcome, String sufix) throws IOException {
File origen = new File(pathSource);
String[] contenidoOrigen = origen.list();
for(String string:contenidoOrigen){
File interno = new File(origen,string);
if (interno.isDirectory()){
copiarArchivos(interno.getPath(),pathOutcome,sufix);
} else {
Path targetOutcome = Paths.get(pathOutcome);
Path targetSource = Paths.get(interno.getPath());
Files.copy(targetSource,targetOutcome);
}
}
}
public static void main(String[] args) throws IOException {
copiarArchivos("Vampiro_Mascarada","pruebaPDF",".pdf");
}
}
My folder structure is like this:
/out
/pruebasPDF
/src
/Vampiro_Mascarada
/1.pdf
/2.pfdf
/Images
/1.png
/2.png
You need to use to Files.copy(source,dest,CopyOption) with the REPLACE_EXISTING option.

getClassLoader().getResourceAsStream method returns null for a file with ".LIB" extension

I'm trying to load a file from resources/ path using
getClassLoader().getResourceAsStream("file.LIB")
but the method always returns null, unless I rename the file into another extension, say ".dll".
I've looked into the official Java documentation, but to no avail.
Why does the method acts strange on that file type?
Note: I'm using JDK 1.8.0_111 x86 (due to constraints on that lib file, which only works well with a 32-bit JVM)
It does works for me, you need to be sure what exactly you are doing with lib file.
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class FileHelper {
public String getFilePathToSave() {
Properties prop = new Properties();
String filePath = "";
try {
InputStream inputStream =
getClass().getClassLoader().getResourceAsStream("abc.lib");
prop.load(inputStream);
filePath = prop.getProperty("json.filepath");
} catch (IOException e) {
e.printStackTrace();
}
return filePath;
}
public static void main(String args[]) {
FileHelper fh = new FileHelper();
System.out.println(fh.getFilePathToSave());
}
}

getResourceAsStream() works on Windows but not on Linux

I have a following class in my project:
package com.test.schedule.payloads;
import com.google.common.base.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Loads payload from file
*/
public class FilePayload{
private static final Logger LOGGER = Logger.getLogger(FilePayload.class);
private final String filename;
public FilePayload(String filename) {
this.filename = filename;
}
public String getAsString() {
try {
return IOUtils.toString(new InputStreamReader(FilePayload.class.getResourceAsStream(filename), Charsets.UTF_8));
} catch (IOException e) {
LOGGER.error("Error while loading file: '" + filename +'\'', e);
return "";
}
}
}
In resources directory of my project (maven one) I have file in following path:
com/test/schedule/payloads/schedule-payload.xml
When I execute getAsString() with filename equal to "schedule-payload.xml" on Windows everything works fine. But when the same code is executed on Linux server it returns null on getResourceAsStream(). I have no idea how to fix it so code works both on Windows and Linux. Any help would be very appreciated.
Check, that everything on your path to this file "com/test/schedule/payloads/schedule-payload.xml" is lowercase, as linux paths are case sensitive and windows paths are not case sensitive.

Problems printing a directory listing to the console

Sorry about readability. Stack appears to be trimming spaces from code lines & indents don't show up. Hrmph.
This was printing to the console without any problems...
CGT\whgdata\whnvp33.txt << EXPECTED OUTPUT (excerpt)
CGT\whgdata\whnvt30.txt
CGT\whgdata\whnvt31.txt
CGT\whgdata\whnvt32.txt
CGT\whgdata\whnvt33.txt
CGT\whgdef.txt
CGT\whgdhtml.txt
CGT\whibody.txt
etc....
...until I tried printing the hashtable to a file. Since that point, getFileListing isn't recognized as a valid symbol.
FileListing2.java:17: error: cannot find symbol
List<File> files = FileListing2.getFileListing(startingDirectory);
symbol: method getFileListing(File)
location: class FileListing2
1 error
Can someone lend a second set of eyes to help me uncover what I accidentally/overwrote. I'm sure it's something obvious. :\
import java.util.*;
import java.io.*;
import java.nio.*;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption.*;
import java.nio.file.Paths;
//
public final class FileListing2 {
public static void main(String... aArgs) {
//
File startingDirectory= new File("CGT");
File outputFile = new File("CGTOutput.txt");
List<File> files = FileListing2.getFileListing(startingDirectory);
OutputStream output = null;
//
for(File file : files ) {
System.out.println(file); //print filenames
}
}
}
If your code is all you have for FileListing2, than there is no getFileListing() method for LileListing2, only a main() method
Yeah it IS something very obious, your class FileListing2 does not contain a method getFileListing(File). And it has to be static, the way you're trying to call it:
public final class FileListing2 {
public static void main(String... aArgs) {
//
File startingDirectory= new File("CGT");
File outputFile = new File("CGTOutput.txt");
List<File> files = FileListing2.getFileListing(startingDirectory);
OutputStream output = null;
//
for(File file : files ) {
System.out.println(file); //print filenames
}
}
public static List<File> getFileListing(File f) {
/* implementation */
}
}

Categories

Resources