6

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"

ess
  • 663
  • 3
  • 9
  • 17
  • what kind of application you are developing? B/S or C/S? if B/S, maybe you could achieve this by `javascript`, but Im not sure. else, you could develop a client side app to create file on client – Rugal Jan 27 '14 at 09:10
  • @Rugal You can't write to the filesystem with JavaScript. – Philipp Gayret Jan 27 '14 at 09:12
  • 1
    If you want this to be done in Java only, you'll have to send a created file back in response, save it to the client-side. – TechSpellBound Jan 27 '14 at 09:12
  • @user1066946 I think it could be `stackedit.io` use it to store text in browser cache. But of course you could not create file that follow your mind because browser wont allow this! – Rugal Jan 27 '14 at 09:13
  • is it a web application or something else ? – aryann Jan 27 '14 at 09:14
  • 1
    i want to create a java web app which creates client side file or a html app with js which creates client side file – ess Jan 27 '14 at 09:28
  • @ess You can't access a client's filesystem from the server, and JavaScript is sandboxed and _not_ allowed access to the filesystem either, you'll have to find a different solution. ( ie; make a clientside applet for it or such. ) – Philipp Gayret Jan 27 '14 at 10:09
  • The main reason why this is not allowed is that it would be a significant security issue. The browser simply can't let a (potentialy unknown) remote server to create arbitrary files on the client machine. – radkovo Jan 27 '14 at 10:19

3 Answers3

1

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.

sayan
  • 501
  • 2
  • 7
  • 21
1

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.

Community
  • 1
  • 1
Arthur Weborg
  • 8,280
  • 5
  • 30
  • 67
-1

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

Ted Hive
  • 14
  • 2
  • @Ted Hive, check out the [w3 HTML5 File-System API Spec](http://www.w3.org/TR/file-system-api/). It's implemented in a couple browsers [check here to see known support](http://caniuse.com/filesystem) – Arthur Weborg Jan 30 '14 at 15:47