create client side file using java - java

i am trying to create a project which create a file in client side . i ave done the coding to create a file .but it obviously will be created in server side.. can any one help to do this. below is the code i have done..
File file = new File("d:/file.txt");
try {
String content = "This is the content to write into file";
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
I have also tried to create a file using filesysapi, which is done using HTML and javascript. but i got "Error: SECURITY_ERR"

Despite what everyone is saying, you can create a client-side file via javascript. It's a sandboxed portion of the File System, done via HTML5's FileSystem API.
HOWEVER, my guess is your SECURITY_ERR is probably because you are opening an html page with the target javascript via File://PATH_TO_HTML_PAGE in your browser. The File-System API Will not work unless your grabbing the html/javascript/css from a server (like locahost:8080/test.html - Netbeans has some options to run a glassfish/server instance pretty painlessly locally on your machine if you have no experience with servers.).
Update 1-31-2014
Found this in an article on the File-System API, which confirmed the above paragraph for me:
You may need the --allow-file-access-from-files flag if you're debugging your app from file://. Not using these flags will result in a SECURITY_ERR or QUOTA_EXCEEDED_ERR FileError.
end update
That said, in the previous comment on a different question you asked and I answered, you were using TEMPORARY Storage. I use PERSISTENT because it is more reliable, and the browser displays a message asking for permission to store the data locally on the target machine. Here is how I have been making files locally on client machines for persistent data storage for the past couple years. This to the best of my knowledge only works with a handful of browser's, I use Google Chrome - the following defeinitely works in Google Chrome.
The following is javascript and needs to be within either an external script or script tags.
//this is a callback function that gets passed to your request for the file-System.
var onInitFs = function(fileSys){
//fileSystem is a global variable
fileSystem = fileSys;
//once you have access to the fileSystem api, then you can create a file locally
makeAFile();
makeAndWriteContent();
};
var errorHandler = function(e){console.log('Error', e);};
//request 1 GB memory in a quota request
//note the internal callback `function(grantedBytes){...}` which makes the actual
//request for the Filesystem, on success `onInitFs` is called.
///on error the `errorHandler` is called
navigator.webkitPersistentStorage.requestQuota(1024*1024*1024*1, function(grantedBytes) {
window.webkitRequestFileSystem(PERSISTENT, grantedBytes, onInitFs, errorHandler);
}, errorHandler);
//this method will only work once the fileSystem variable has been initialized
function makeAFile(){
var callbackFunctionOnSuccess = function(){console.log("created new file")}
fileSystem.root.getFile("test.txt", {
create: true
}, callbackFunctionOnSuccess, function(error){console.log(error);});
}
function makeAndWriteContent(){
//this is going to be passed as a callback function, to be executed after
//contents are written to the test2.txt file.
var readFile = function(){
fileSystem.root.getFile("test2.txt", {create: false}, function(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
console.log(this.result);
};
reader.readAsText(file);
}, function(error){console.log(error);});
}, function(error){console.log(error);});
}
fileSystem.root.getFile("test2.txt", {
create: true
}, function(fileEntry) {
fileEntry.createWriter(function(writer) {
writer.onwriteend = function(e) {
writer.onwriteend = function(e){
//now, we will read back what we wrote.
readFile();
}
writer.onerror = function(e3){console.log(e3);
}
var blob = new Blob(["Hello World"]);
writer.write(blob);
};
writer.onerror = function(e3) {console.log(e3);};
//make sure our target file is empty before writing to it.
writer.truncate(0);
}, errorHandler);
}, errorHandler);
}
One thing to keep in mind is that the File-System API is asynchronous so you have to get use to using callback functions. If you try to access the File-System API before it's instantiated, or if you try to access files before they are ready, you will also get errors. Callback functions are essential.

using socket programming, 1st create a communication between server and client machines.
Socket kkSocket = new Socket(hostName, portNumber)
then use File file = new File("hostname#d:/file.txt");
if your host file does not contain hostname IP address maping, then instead of giving hostname, use IP address.

You can not create file on client side because browser does not allow doing that.

Related

FileWriter to write to user desktop in Java, rather than server desktop

As part of a search application, I want the user to be able to download a report showing the results in a CSV file. I have the following method:
public void downloadCustomerResults(String customer) {
String output = "";
output += produceCustomerID(customer);
output += produceCustomerAddress(customer);
output += produceCustomerContactDetails(customer);
output += produceOrderHeader(customer);
output += producePayments(customer);
// Writes to server desktop, not user desktop.
try {
Writer fileWriter = new FileWriter("C:\\Users\\username\\Desktop\\SAR" + customer + "C.csv");
fileWriter.write(output);
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
This downloads the file to the desktop of the machine running the server, not the user's desktop (accessing the app via JSP's on Tomcat). How would I change the file path string to make this download to the users' desktop? Or would I have to pass the file to the JSP for the user to download via their browser?
Thanks.
Short answer: The server has no means of accessing the client's filesystem.
Longer answer: You might either provide a service for the client to download the file (e.g. a webservice accessible through a URI, like #Kayaman mentioned) or the client provides you a service to write the file (e.g. a remote file system, an FTP server etc.). For the latter there might be libraries providing a special java.nio.FileSystem extension.
You may also provide an application running on the client to receive the file. This client application will then have acces to the client's file systems (unless it lacks the access rights, of course).
So the answer I found was to use the JavaScript package FileSaver.js.
This accepts a blob created from a string, and then saves it with a filename of your choice to the browsers preferred download folder.
I managed to pass the string from Java to JavaScript, and then pass it through FileSaver.js in the .JSP page.

Read a file from shared location with access restrictions (java)

I have a program that has to read a file from network location - something like this
String sFileSource = "//MyShared/location/fileName.txt" ;
File inputFile = new File(sFileSource);
try {
ffBuffer = new BufferedReader(new FileReader(inputFile));
}
catch (FileNotFoundException e) { // should never happen
}
Now, the problem is that that shared location is on the different network domain and accessible only using domain credentials
How can I embed entering the credentials into this java program ? The problem is that when ran from different PCs it fails due to login.
Reading a file like that is not a secure way to do it, because you will expose your user domain credentiels.
Reversing the java app could lead to that, so it's better to use an ftp server for that.
The way I have done it before:
Read remote file in java which needs username and password

FTPSclient not working properly on new FTPS server

We will be moving to our own ftps server in the near future from a customer's ftps server. I just tried the existing code but it doesn't work correctly with our new server.
The login seems to work and I can use printWorkingDirectory() and see that I'm in the correct directory on the server. But we can't upload files or list the files in the working directory. listFiles() and printWorkingDirectory() return an empty string or an empty array, although files are in the working directory.
IIRC we had similar issues on the old FTPS server and could fix it by entering passive mode. But neither enterLocalPassiveMode() nor enterLocalActiveMode() work. Also leaving that line out completely doesn't help
The server itself works fine when connecting with FileZilla, so I guess the problem lies within our code but since we don't get an error message it's hard to guess what the problem is.
Here's the version that worked on the old server (using cfscript on Lucee 5.1.2.24):
var oFTPSclient = CreateObject("java", "org.apache.commons.net.ftp.FTPSClient").init("ssl",false);
oFTPSclient.connect( 'our.ftp.server');
oFTPSclient.enterLocalPassiveMode();
oFTPSclient.login( 'user', 'password');
var qFiles = DirectoryList(
path = '/path/to/files/to/upload',
filter = "*.jpg",
listInfo = "query"
);
// Upload files
for( var oFile IN qFiles) {
// Create path to source file
var sSourceFilePath = ExpandPath( oFile.directory & '/' & oFile.name);
// Create java file object
var oJavaFile = CreateObject( "java", "java.io.File").init( sSourceFilePath);
// open input stream from file
var oFileInputStream = CreateObject("java", "java.io.FileInputStream").init( oJavaFile);
// Set file transfer to binary
oFTPSclient.setFileType( oFTPSclient.BINARY_FILE_TYPE);
// store current file to server
oFTPSclient.storeFile( oFile.name, oFileInputStream);
oFileInputStream.close();
}
oFTPSclient.disconnect();
When we try to upload files, the loop finishes, but way to quickly (our connection is rather slow here, so a few megabytes should not be uploaded instantly) and the disconnect() call at the end times out.
Any ideas where to start debugging? Or is my initial assumption that it's a problem with the code wrong and it's a problem with the server and we should rather look into that?
Update:
Due to the length, I have posted FileZilla's verbose log here: http://pastebin.com/b9TfR7cg

Apache FTPClient

I'm writing a very simple FTPClient application using Apache's library.
All I do is download a jar file from a server. There is no exception, the application works fine when I run in on MacOS and as soon as I run the same code in Windows the downloaded file is smaller than the file on server. However, there is no exception and everything seems to be fine.
I'm going crazy, I'm using binary mode and the code is so simple I can't believe I've been stuck on it since yesterday!!!
Please help!
public boolean loadLatest(){
FTPClient ftp = new FTPClient();
try {
ftp.connect("server address");
ftp.setControlKeepAliveTimeout(300);
ftp.enterLocalPassiveMode();
String fu = "username";
ftp.login(fu, "password");
int reply = ftp.getReplyCode();
if (FTPReply.isPositiveCompletion(reply)) {
ftp.setFileTransferMode(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
FTPFilter filter = new FTPFilter();
FTPFile[] finfo = ftp.listFiles(".",filter);
if (finfo.length==0){
return false;
}
File currentJar = new File("sm.jar");
FileOutputStream output;
output = new FileOutputStream("sm.jar");
if (ftp.retrieveFile(finfo[0].getName(), output)==false){
System.out.println("Bad file!");
}
output.close();
ftp.logout();
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
Here is my code:
Thanks
You may have misused the Apache API.
public boolean setFileTransferMode(int mode) throws IOException
Sets the transfer mode. The default transfer mode FTP.STREAM_TRANSFER_MODE if this method is never called or if a connect method is called.
The possible values are STREAM_TRANSFER_MODE, STREAM_TRANSFER_MODE, or BLOCK_TRANSFER_MODE.
So your following line :
ftp.setFileTransferMode(FTP.BINARY_FILE_TYPE);
Is not valid use of the API, and does not setup the client to work in BINARY mode.
The FTP transfert mode as you call it, is actually controled by another method :
public boolean setFileType(int fileType) throws IOException
Sets the file type to be transferred. This should be one of FTP.ASCII_FILE_TYPE , FTP.BINARY_FILE_TYPE, etc. The file type only needs to be set when you want to change the type. After changing it, the new type stays in effect until you change it again. The default file type is FTP.ASCII_FILE_TYPE if this method is never called.
The server default is supposed to be ASCII (see RFC 959), however many ftp servers default to BINARY. To ensure correct operation with all servers, always specify the appropriate file type after connecting to the server.
N.B. currently calling any connect method will reset the type to FTP.ASCII_FILE_TYPE.
Most probably, you need to use this last method to change the mode to BINARY, and your transfer should be OK.

Want to create a servlet that will save the posted data to a file based on a guid filename

So I pushed my java app to a server, pretty excited about that.
Now I want to test something, how can I save the posted data to my servlet to a file, and the filename should be a unique guid.
I have this so far:
public class TestServlet extends javax.servlet.http.HttpServlet {
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
throws javax.servlet.ServletException, IOException {
}
protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
throws javax.servlet.ServletException, IOException {
PrintWriter printWriter = response.getWriter();
printWriter.print("hello, world from testservlet!");
}
}
So assuming the http posted data (say around 50K) will be posted to the field 'payload', how can I grab the posted text, and save it to a file, with the filename being a GUID.
Does java have a construct to clean up an open file, like in c#:
using(var file = new ....)
{
// write to file
}
That closes the connection and cleans up memory etc.
Also, do I need to set special permissions for tomcat to save this file?
I just set things up by default right now (just playing around on a VPS) using ubuntu 11, installed tomcat6.
Thanks.
You can user request to read the "payload", see the API doc for ServletRequest:
request.getParameter("payload");
You can use File to create the file, see AP doc:
File newFile = new File("fileName");
boolean isCreated = newfile.createNewFile();
You can write to the file as follows,
BufferedWriter out = new BufferedWriter(new FileWriter(newFile));
out.write(payLoad);
out.close();
For GUID you see this Create a GUID in Java
And for the clean up, you don't have to worry about it in Java, it's Garbage Collector ( What is the garbage collector in Java? ) does it for you automatically when the reference goes out of scope.
But you should close the resources like out.close to release it back to the system when you are done with it.
Also, do I need to set special permissions for tomcat to save this file?
You do not need to do that because tomcat is just a server, it's more related to the file system (OS). I use Glassfish on Unix and I don't need to do anything like that to create file.
Now I want to test something, how can I save the posted data to my servlet to a file, and the filename should be a unique guid.
Use File#createTempFile() to create a file with an unique ID in the given folder.
File file = File.createTempfile("prefix-", ".ext", "/path/to/files");
// ...
See also:
Saving uploaded file in specific location
Does java have a construct to clean up an open file, like in c#: using?
Only in Java 7 which is already been out for some time.
try (FileWriter writer = new FileWriter(file)) {
writer.write(content);
}
which is equivalent to
FileWriter writer = null;
try {
writer = new FileWriter(file);
writer.write(content);
} finally {
if (writer != null) writer.close();
}
See also:
"using" keyword in java
Also, do I need to set special permissions for tomcat to save this file?
The user who has started Tomcat should indeed have the file write permissions on the given directory.
In the future please ask separate questions in separate SO questions.
Java 7 has a new try with resources construct that will take care of closing the file for you. Otherwise... just close the file; no big deal.
As far as "special permissions", as long as the user Tomcat is running under can access the directory in question, there's no issue. I'd recommend against storing it under the webapp directories, though (and if it's deployed as a war you may not be able to anyway). Keep uploaded files in a known, but separate, directory.

Categories