I have this file sharing program, where i can get mye files from a local location JFileChooser chooser = new JFileChooser("C://Users"), but i want to get files from a Server using an IP address. I have trying String hostname = "192.168.1.1"; but its not working. When i open the file chooser i get to my own folder. some tips?
public void download(String username) throws RemoteException, NullPointerException{
JFileChooser chooser = new JFileChooser("//" + hostname + "/C://");
chooser.setFileView(new FileView() {
#Override
public Boolean isTraversable(File f) {
return (f.isDirectory() && f.getName().equals("C://"));
}
});
int returnVal = chooser.showOpenDialog(parent);
if (returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName());
} try {
String fileName = chooser.getSelectedFile().getName();
File selectedFile = chooser.getSelectedFile();
//String name = "//" + hostname + "/chatter";
System.out.println(fileName);
//ChatFront cf = (ChatFront) Naming.lookup(name);
String ClientDirectory = getProperty + "/desktop/";
byte[] filedata = cf.downloadFile(selectedFile);
File file = new File(fileName);
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(ClientDirectory + file.getName()));
output.write(filedata, 0, filedata.length);
notifySelf(getUsername(), "You have now downloaded: " + file.getName() + " from the server");
output.flush();
output.close();
} catch (Exception e) {
System.err.println("FileServer exception: " + e.getMessage());
e.printStackTrace();
}
}
Thanks in Advance :)
You're using "//" + hostname + "/C://" as the path for your JFileChooser. That's not a valid path. If you're trying to access files in a shared folder on a LAN, the path for that looks like \\hostname\sharename.
Even if no shared folders have been defined on the remote machine, may be an "administrative share" of the C: drive called C$, so you could use \\hostname\C$. But you have to authenticate as a valid user on that system to have permission to access the share. (I'm not sure how that'll work when you try to acccess the path from a Java program — Windows might pop up a login box for the remote system, or it might just fail.)
Related
I'm trying to make a launcher for my Java desktop application (separated applications), which has to look for an updated version of the main application on the server. My idea is to store the app version inside of a text file on each side.
I found (thanks to Google san) the way to read the version from the text file and download the jar directory with all of it's content (both on server side). I'm using the Apache Commons Net FTP library btw.
The problem comes when I try to download the jar directory from the server after beeing reading the text file. I get the text file content correctly, the files download fails though.
If I switch code lines to download the stuff first and then read the text file, both of them works well, but we all know that's not the way an update check should be.
I've been looking and I don't get what I'm doing wrong. It's my first time working with this library.
This is the code I'm working with:
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
class FTPUtil{
private String server = "www.server.host";
private int port = 21;
private String user = "user";
private String pass = "password";
private FTPClient ftpClient = new FTPClient();
public void Connect() throws IOException{
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
System.out.println("Connected");
}
public void Disconnect() throws IOException{
ftpClient.logout();
ftpClient.disconnect();
System.out.println("Disconnected");
}
public double getServerVersion(String remoteDirPath) throws IOException{
InputStream inputStream = ftpClient.retrieveFileStream(remoteDirPath + "/version.txt");
return Double.parseDouble(IOUtils.toString(inputStream, "UTF-8"));
}
public boolean downloadSingleFile(String remoteFilePath, String savePath) throws IOException{
File downloadFile = new File(savePath);
File parentDir = downloadFile.getParentFile();
if(!parentDir.exists())
parentDir.mkdir();
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(downloadFile));
try{
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
return ftpClient.retrieveFile(remoteFilePath, outputStream);
}catch(IOException e){
throw e;
}finally{
if(outputStream != null)
outputStream.close();
}
}
public void downloadDirectory(String parentDir, String currentDir, String saveDir) throws IOException{
String dirToList = parentDir;
if(!currentDir.equals(""))
dirToList += "/" + currentDir;
FTPFile[] subFiles = ftpClient.listFiles(dirToList);
if(subFiles != null && subFiles.length > 0){
for(FTPFile aFile : subFiles){
String currentFileName = aFile.getName();
// skip parent directory and the directory itself
if(currentFileName.equals(".") || currentFileName.equals(".."))
continue;
String filePath = parentDir + "/" + currentDir + "/" + currentFileName;
if(currentDir.equals(""))
filePath = parentDir + "/" + currentFileName;
String newDirPath = saveDir + parentDir + File.separator + currentDir + File.separator + currentFileName;
if(currentDir.equals(""))
newDirPath = saveDir + parentDir + File.separator + currentFileName;
if(aFile.isDirectory()){
// create the directory in saveDir
File newDir = new File(newDirPath);
boolean created = newDir.mkdirs();
if(created)
System.out.println("CREATED the directory: " + newDirPath);
else
System.out.println("COULD NOT create the directory: " + newDirPath);
// download the sub directory
downloadDirectory(dirToList, currentFileName, saveDir);
}else{
// download the file
boolean success = downloadSingleFile(filePath, newDirPath);
if(success)
System.out.println("DOWNLOADED the file: " + filePath);
else
System.out.println("COULD NOT download the file: " + filePath);
}
}
}
}
}
import java.io.IOException;
public class Main{
public static void main(String[] args){
String project = "ServerFolderName";
String remoteDirPath = "/" + project;
String saveDirPath = "C:/Users/username/Desktop";
FTPUtil ob = new FTPUtil();
try{
ob.Connect();
System.out.println(ob.getServerVersion(remoteDirPath));
ob.downloadDirectory(remoteDirPath, "", saveDirPath);
ob.Disconnect();
}catch(IOException e){
e.printStackTrace();
}
}
}
And the console output:
run:
Connected
1.0
Exception in thread "main" org.apache.commons.net.ftp.parser.ParserInitializationException: Unknown parser type: 0.000 seconds (measured here), 37.12 Kbytes per second
at org.apache.commons.net.ftp.parser.DefaultFTPFileEntryParserFactory.createFileEntryParser(DefaultFTPFileEntryParserFactory.java:170)
at org.apache.commons.net.ftp.parser.DefaultFTPFileEntryParserFactory.createFileEntryParser(DefaultFTPFileEntryParserFactory.java:94)
at org.apache.commons.net.ftp.FTPClient.__createParser(FTPClient.java:3381)
at org.apache.commons.net.ftp.FTPClient.initiateListParsing(FTPClient.java:3338)
at org.apache.commons.net.ftp.FTPClient.listFiles(FTPClient.java:3016)
at generateupdateinfo.FTPUtil.downloadDirectory(FTPUtil.java:58)
at generateupdateinfo.Main.main(Main.java:13)
C:\Users\username\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
Maybe I'm going the wrong way doing this launcher/updater, I'm open to suggestions and new ideas to achieve it.
Edit:
I noticed that it works if I renew the server connection with Disconnect() and Connect() after reading the text file and before downloading the files. I still feel should be another way, doesn't look quite good.
ob.Connect();
System.out.println(ob.getServerVersion(remoteDirPath));
ob.Disconnect();
ob.Connect();
ob.downloadDirectory(remoteDirPath, "", saveDirPath);
ob.Disconnect();
I found the problem. Apparently I just have to flush the server replies with ftpClient.completePendingCommand() after reading the version from the text file. I still do not get why happens just with one of both processes though, I would like to understand.
Thanks!:)
I can create file. It's creating on /data/data/com.mypackage.app/files/myfile.txt. But i want to create on Internal Storage/Android/data/com.mypackage.app/files/myfiles.txt location. How can i do this?
Codes:
public void createFile() {
File path = new File(this.getFilesDir().getPath());
String fileName = "myfile.txt";
String value = "example value";
File output = new File(path + File.separator + fileName);
try {
FileOutputStream fileout = new FileOutputStream(output.getAbsolutePath());
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(value);
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
UPDATE :
I fixed the problem. Maybe someones to helps. Only changing this line.
File output = new File(getApplicationContext().getExternalFilesDir(null),"myfile.txt");
You can use the following method to get the root directory:
File path = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
Instead of DIRECTORY_PICTURES you can as well use null or DIRECTORY_MUSIC, DIRECTORY_PODCASTS, DIRECTORY_RINGTONES, DIRECTORY_ALARMS, DIRECTORY_NOTIFICATIONS, DIRECTORY_PICTURES, or DIRECTORY_MOVIES.
See more here:
https://developer.android.com/training/data-storage/files.html#WriteExternalStorage
https://developer.android.com/reference/android/content/Context.html#getExternalFilesDir(java.lang.String)
The following code works like a charm in eclipse under windows:
public static void main(String[] args)
{
try
{
String filePath = "\\\\myserver\\dir";
String fileName = "myFile.txt";
FileWriter myFileWriter = new FileWriter(filePath + File.separator + fileName);
BufferedWriter myBufferedWriter = new BufferedWriter(myFileWriter);
myBufferedWriter.write("test");
myBufferedWriter.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
Now I want to run this code from a unix machine in the same network. The program runs, but does not write my file or throws an exception. Any ides ?
Cheers
If that destination unix machine has Samba installed you might want to try the following library:
http://jcifs.samba.org/
You would need a username and password though.
try {
String filePath = "myserver/dir";
String fileName = "myFile.txt";
String user = "username";
String password = "password";
// URL: smb://user:passwd#host/share/filname
SmbFileOutputStream out = new SmbFileOutputStream("smb://" + user + ":" + password + "#" + filePath
+ File.separator + fileName);
out.write("test".getBytes());
out.close();
} catch (Exception e) {
e.printStackTrace();
}
This would also work with a windows machine as the destination if the server is configured as an SMB server.
Because in Unix/Linux this is not the right path
String filePath = "\\\\myserver\\dir";
I suggest to check such path exist, and 99% chances you will not have permission to create them. It would be more or less
String filePath = "/usr/xx/";
Creating folder:
File temp = new File("temp");
boolean test = temp.mkDir();
Hello i m trying to upload file using java file.. but i don't get it.. i get file size=0 i'm providing here my java code. tell me why i cant upload on particular folder. i want to store my file in particular folder. i am trying to get file size, file name but i got the null value where am i wrong please tell me.
public void updateTesti(ActionRequest actionRequest,ActionResponse actionResponse) throws IOException, PortletException
{
//image upload logic
String folder_for_upload =(getPortletContext().getRealPath("/"));
//String folder=actionRequest.getParameter("uploadfolder");
realPath=getPortletContext().getRealPath("/");
logger.info("RealPath is" + realPath);
logger.info("Folder is :" + folder_for_upload);
try
{
logger.info("Admin is try to upload");
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
if (uploadRequest.getSize("fileName") == 0) {
SessionErrors.add(actionRequest, "error");
}
String sourceFileName = uploadRequest.getFileName("fileName");
File uploadedFile = uploadRequest.getFile("fileName");
System.out.println("Size of uploaded file: " + uploadRequest.getSize("fileName"));
logger.info("Uploded file name is: " + uploadRequest.getFileName("fileName"));
String destiFolder=("/home/ubuntu/liferay/liferay-portal-6.1.1-ce-ga2/tomcat-7.0.27/webapps/imageUpload-portlet/image");
String newsourcefilename = (uploadRequest.getFileName("fileName"));
File newFile = new File(destiFolder +"/"+ newsourcefilename);
logger.info("New file name: " + newFile.getName());
logger.info("New file path: " + newFile.getPath());
InputStream in = new BufferedInputStream(uploadRequest.getFileAsStream("fileName"));
FileInputStream fis = new FileInputStream(uploadedFile);
FileOutputStream fos = new FileOutputStream(newFile);
byte[] bytes_ = FileUtil.getBytes(in);
int i = fis.read(bytes_);
while (i != -1) {
fos.write(bytes_, 0, i);
i = fis.read(bytes_);
}
fis.close();
fos.close();
Float size = (float) newFile.length();
System.out.println("file size bytes:" + size);
System.out.println("file size Mb:" + size / 1048576);
logger.info("File created: " + newFile.getName());
SessionMessages.add(actionRequest, "success");
}
catch (FileNotFoundException e)
{
System.out.println("File Not Found.");
e.printStackTrace();
SessionMessages.add(actionRequest, "error");
}
catch (NullPointerException e)
{
System.out.println("File Not Found");
e.printStackTrace();
SessionMessages.add(actionRequest, "error");
}
catch (IOException e1)
{
System.out.println("Error Reading The File.");
SessionMessages.add(actionRequest, "error");
e1.printStackTrace();
}
}
You need to do this to upload small files < 1kb
File f2 = uploadRequest.getFile("fileupload", true);
They are stored in memory only. I have it in my catch statement incase I get a null pointer - or incase my original file (f1.length) == 0
I have executed your code.It is working as per expectation.There might be something wrong in your jsp page.I am not sure but might be your name attribute is not same as the one which you are using in processAction(assuming that you are using portlet).Parameter is case sensitive,so check it again.
You will find more on below link.It has good explanation in file upload.
http://www.codeyouneed.com/liferay-portlet-file-upload-tutorial/
I went through a file upload code, and when i implement that in my local system what i got is, portlet is saving the file i upload in tomcat/webbapp/abc_portlet_project location, what i dont understand is from where portlet found
String folder = getInitParameter("uploadFolder");
String realPath = getPortletContext().getRealPath("/");
System.out.println("RealPath" + realPath +"\\" + folder); try {
UploadPortletRequest uploadRequest =
PortalUtil.getUploadPortletRequest(actionRequest);
System.out.println("Size: "+uploadRequest.getSize("fileName"));
if (uploadRequest.getSize("fileName")==0)
{SessionErrors.add(actionRequest, "error");}
String sourceFileName = uploadRequest.getFileName("fileName"); File
file = uploadRequest.getFile("fileName");
System.out.println("Nome file:" +
uploadRequest.getFileName("fileName")); File newFolder = null;
newFolder = new File(realPath +"\" + folder);
if(!newFolder.exists()){ newFolder.mkdir(); }
File newfile = null;
newfile = new File(newFolder.getAbsoluteFile()+"\"+sourceFileName);
System.out.println("New file name: " + newfile.getName());
System.out.println("New file path: " + newfile.getPath());
InputStream in = new
BufferedInputStream(uploadRequest.getFileAsStream("fileName"));
FileInputStream fis = new FileInputStream(file); FileOutputStream fos
= new FileOutputStream(newfile);
I have a database on my Android phone, and I need to get the information onto an SD card.
Is it possible to save the database file onto the SD card in a readable state? I haven't been able to find any information on how to do this.
Some source code that copies the database file to an SD card would be ideal.
The database file is just like any other file, if you make a binary file copy it will work.
Java has no built in file copy method, so you can use this:
Standard concise way to copy a file in Java?
Just don't forget to add your manifest permission to write to the SD card:
Permission to write to the SD card
Here's a script I've bastardized from several other users on SO. It looks like you can tell android where to store the file, but when you go into the phone with adb shell you might have a hard time finding it!
This code (which I mapped to a temporary button in my action bar for debugging) would print something like: "database saved to: /storage/emulated/0/DB-DEBUG/todotable.db", but going into the shell on my phone I actually found my database at: "/storage/emulated/legacy/DB-DEBUG/"... not sure what's up with that, but now I can check out my database with an sqlite browser!
//db will reside in: /storage/emulated/legacy/DB_DEBUG
private void copyDatabase(Context c, String DATABASE_NAME) {
String databasePath = c.getDatabasePath(DATABASE_NAME).getPath();
File f = new File(databasePath);
OutputStream myOutput = null;
InputStream myInput = null;
Log.d("testing", " testing db path " + databasePath);
Log.d("testing", " testing db exist " + f.exists());
if (f.exists()) {
try {
File directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/DB-DEBUG");
if (!directory.exists()){
directory.mkdir();
}
String copyPath = directory.getAbsolutePath() + "/" + DATABASE_NAME;
myOutput = new FileOutputStream(copyPath);
myInput = new FileInputStream(databasePath);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
Toast.makeText(getBaseContext(), "Your database copied to: " + copyPath, Toast.LENGTH_LONG).show();
Log.d("testing", " database saved to: " + copyPath);
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
} finally {
try {
if (myOutput != null) {
myOutput.close();
myOutput = null;
}
if (myInput != null) {
myInput.close();
myInput = null;
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}