I am trying to place a file into SFTP directory using JSch.
channelSftp.cd(destDir);
channelSftp.put(new FileInputStream(filePath), filePath.substring(filePath.lastIndexOf(File.separatorChar)));
But the above code is placing the file always in the SFTP user home directory instead of destDir. For example, if I create a subdirectory test under user home directory and set destDir as channelSftp.getHome()+"test", still the file is being copies to user home directory only instead of test sub-directory.
I tried to list files in destDir (test sub-directory), it is showing all files/directories under test directory.
Vector<com.jcraft.jsch.ChannelSftp.LsEntry> vv = channelSftp.ls(destDir);
if(vv != null) {
for(int ii=0; ii<vv.size(); ii++){
Object obj=vv.elementAt(ii);
if(obj instanceof LsEntry){
System.out.println(((LsEntry)obj).getLongname());
}
}
}
Any suggestions? I looked at permissions (test sub-directory has exactly same permissions as SFTP user home directory).
filePath.substring(filePath.lastIndexOf(File.separatorChar)) result includes even the last separator.
So if you pass /home/user/file.txt, you get /file.txt. That is an absolute path, so any working directory is disregarded and you effectively always write to a root folder.
You want filePath.substring(filePath.lastIndexOf(File.separatorChar) + 1) to get only file.txt.
See also How do I get the file name from a String containing the Absolute file path?
This works for very well !!
channel.connect();
try {
channel.mkdir("subdir");
} catch (Exception e) {
// ... do something if subdir already exists
}
// Then the trick !
channel.put(inputStream, "subdir" + "/" + "filename.ext");
Related
I want to check if the asset in Assets directory of my Android App is a File or a Directory.
I have already tried every solution available anywhere on internet including StackOverflow.
Most of the solutions use
File myFile = new File(path);
then check for
myFile.isDirectory();
or
myFile.isFile();
But it works only if I have my files and directories anywhere else other than under the Assets directory.
Any suggestions will be highly appreciated.
Here is a solution to my problem that I found out working 100% listing all directories and files even sub-directories and files in subdirectories. It also works for multiple levels.
Note: In my case
Filenames had a . in them. i.e. .htm .txt etc
Directorynames did not have any . in them.
Note: about -- path --
to get all files and directories in Assets root folder
String path = ""; // assets
or to get files and directories in a subfolder use its name as path
String path = "html"; // <<-- assets/html
listAssetFiles2(path); // <<-- Call function where required
//function to list files and directories
public void listAssetFiles2 (String path){
String [] list;
try {
list = getAssets().list(path);
if(list.length > 0){
for(String file : list){
System.out.println("File path = "+file);
if(file.indexOf(".") < 0) { // <<-- check if filename has a . then it is a file - hopefully directory names dont have .
System.out.println("This is a folder = "+path+"/"+file);
if(path.equals("")) {
listAssetFiles2(file); // <<-- To get subdirectory files and directories list and check
}else{
listAssetFiles2(path+"/"+file); // <<-- For Multiple level subdirectories
}
}else{
System.out.println("This is a file = "+path+"/"+file);
}
}
}else{
System.out.println("Failed Path = "+path);
System.out.println("Check path again.");
}
}catch(IOException e){
e.printStackTrace();
}
}
Thanks
Instead of letting a dot in a name determine what should happen you should check if it is a file or a directory. Make your own isDirectory(name) function by trying to open an InputStream for the file/directory. If you succeed it is a file. If you get an exception its a directory. Dont forget to close the stream when done.
So, my I have a method that saves some data in a properties file but something weird happens. See, lets say I have the JAR file on desktop. If I open it directly from there (double click, etc) the properties file is saved in the desktop, as should be. However, if you drag the JAR to the Windows start list and open it from there, the properties file will be saved in the System32 folder.
Here is the method:
private void saveAncientsData() {
Properties prop = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream("ancients.data");
File file = new File("ancients.data");
// set the properties value
for (int x = 0; x < currentLvlSpinnerFields.size(); x++) {
prop.setProperty(ancientNames[x], currentLvlSpinnerFields.get(ancientNames[x]).getValue().toString());
}
// save properties to project root folder
prop.store(output, null);
JOptionPane.showMessageDialog(this, "Data successfully saved in \n\n" + file.getCanonicalPath(), "Saved", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Would appreciate any help, since I am clueless.
Thanks in advance!
according to your code you haven't give path of property file to create in desktop.
output = new FileOutputStream("ancients.data");
so your property file will be created in same directory where your jar file exists .
but if you run this .jar file from a parent process your jar file created in the directory where that parent process exists.
i guess when windows starts a specific process exist in win32 directory execute start-up programs .i think it's userinit.exe . so your prop file will be created in System32 directory .
if you want property file to create in desktop you can put your jar file in desktop and add a shortcut to .jar or you can give full-path to your desktop like
output = new FileOutputStream(System.getProperty("user.home") + "/Desktop/"+"ancients.data");
edit
to understand this problem
1) create a folder named example in desktop.and then create 2 folders path1 and path2 .then add .jar to path1 folder
2) double click jar in path1 .and a property file will be created in path1 as you expected .
3) delete property file.open command prompt in path2 . To run Prop.jar file in path1 . type call "pathtodesktop/example/path1/Prop.jar" hit enter.
.property file will be created in path2 instead of path1 that's what happening in your case.
I am writing a Java program to convert an XLS file to a CSV file for some Python parsers to act on them.
Everyday on my desktop (I'm using Ubuntu btw) I have a folder called "DFiles" inside which there is another folder called "20140705" (this folder is dynamicalle generated, tomorrow some other program deletes this folder and makes a new folder called 20140706 in its place). Inside this folder there is an xls file whose name is always "data.xls". I already have the code to convert it to CSV.
So here's my problem. Tomorrow my code my run on someone else's desktop(which is also Ubuntu). So when giving the path
input_document = new FileInputStream(new File("/home/local/TNA/srini/Desktop/DFiles/20140705/data.xls"+));
This unfortunately will work only today and only on my computer.
Ideally, I would like to do some thing like set the path to "$HOME/Desktop/Dfiles/2*/data.xls" as the file path. So how can I use bash env variables and wild cards in a file path in java?
You can get the value of an environment variable using System.getenv(...):
String homeDir = System.getenv("HOME");
String directory = homeDir + "/Desktop/DFiles/...";
Wildcards: That will not work. You can use listFiles() to list the files and directories inside a certain directory.
File dir = new File(homeDir + "/Desktop/DFiles";
for (File f : dir.listFiles()) {
if (f.isDirectory()) {
System.out.println("Found subdirectory: " + f.getName());
} else {
System.out.println("Found file: " + f.getName());
}
}
You can write some code that recursively goes into the subdirectories and picks up any file of which the name ends with '.xls'.
I have read all the other questions related to this in StackOverflow and I did not find any clear response.
To cut it short, I have an application that will store some files in a directory that I will use than to process them. I have intentions of moving my app in different places (other computers) so I need to have a relative path to work with so that I will not change that in each time.
Does anyone know how to get the relative path of the application (not the full path) so that I could use in this case? If what I am asking is not wright please tell me another way to achieve what I need. Thank you
Just use "./".
No matter what directory your application has been launched from, "./" will always return that directory.
For example:
new File("./") will return a file object pointed at the directory your java application has been launched from
new File("./myDirectory") will return a file object pointed at the myDirectory folder located in the directory your java application has been launched from
Here is one approach:
I believe you need to define the path of directory containing the files in a configuration/property file. You can change the path in the configuration file when you move your application or the directory containing the file. This is how your properties file(let's say config.properties) contents should be:
filesDirPath=\usr\home\test
And this what you should do in the code:
private void readConfig()
{
Properties prop = new Properties();
try {
//load a properties file
prop.load(new FileInputStream("config.properties"));
//get the directory path property value
String flesDirPath = prop.getProperty("filesDirPath");
System.out.println("Files to be read are located in dir : " + flesDirPath );
} catch (IOException ex) {
ex.printStackTrace();
}
}
I trying to check whether a file exists at given directory location.
File seacrhFile = new File("D:/input", contract.conf);
if (seacrhFile.exists()) {
returnFile = seacrhFile;
} else {
System.out.println("No such file exists");
}
reutrn returnFile;
This is working in D:/input directory scenario, but if I Change the directory location to src/test/resources/input folder then I am getting No such file exists, eventhough the file exists.
If you want to have access to
src/test/resources/input
you probably should use
System.getProperty("user.dir") + File.separator + "src/test/resources/input"
because the system-property "user.dir" points to the projectlocation.
If you just use "src/test/resources/input" you will get your mentioned exception, because the File Object don't "start" at the project location. So you have to specify it manually.
Nevertheless it's better to use the getResource-Method to retrieve different resources within your project, because if you run your project with the jar-File you need to tweak around to get "user.dir" to work correctly.
Just a basic example for the Classloader:
ClassLoader.getSystemClassLoader().getResource("test/resources/input");
This returns an URL-Object, with this object you can get the File-Object using ...
URL filePath = ClassLoader.getSystemClassLoader().getResource("test/resources/input");
File file = new File( filePath.toURI() );
Remove the src and try it again .