File Upload on a remote Windows Machine

I was trying some stuff out and nothing spectacular. Thought I would put the code down for future. Will need to verify the code for other OSs.

package com.file.upload.windows;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileUploader {

    public static void main(String[] args) {
	FileUploader fileUploader = new FileUploader();
	fileUploader.upload();
    }

    public void upload() {
	File file = new File("\\\\<PC NAME>\\<FOLDER NAME>\\test.txt");
	if (file.exists()) {
	    throw new RuntimeException(
		"File already created!");
	} else {
	    try {
		boolean fileCreated
		    = file.createNewFile();
		if (fileCreated) {
		    BufferedWriter bw
		        = new BufferedWriter(new FileWriter(file));
		    bw.write("Testing the File transfer Protocol");
		    bw.close();
		 } else {
		    System.out.println("Unable to create file");
		}
	    } catch (IOException e) {
		e.printStackTrace();
	    }
	}
    }

}

The only point to note is the URL path. “\\\\<PC NAME>\\<FOLDER NAME>\\test.txt”. Each backward slash is replaced by an additional escape backslash. Hence the path of \\<PC NAME>\<FOLDER NAME>\test.txt becomes \\\\<PC NAME>\\<FOLDER NAME>\test.txt

Have the above source on a Windows based client machine. Need to verify for other OSs. Probably for Linux or Unix we might need a FTP or SFTP server.

Advertisements

2 thoughts on “File Upload on a remote Windows Machine

  1. Hi,

    I tried your code, but I got the following exception:

    java.io.FileNotFoundException: \\keqiang-xp-2\share\test.txt (Access is denied)
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.(Unknown Source)
    at java.io.FileOutputStream.(Unknown Source)
    at java.io.FileWriter.(Unknown Source)
    at test.rim.bbapps.eclipse.resultpublish.dialogs.test.upload(test.java:210)
    at test.rim.bbapps.eclipse.resultpublish.dialogs.test.main(test.java:53)

    It seems like we need permission to write to file to the other remote machine.

  2. That’s right. The remote machine you are accessing would need to provide you appropriate access rights (read/write) to the specific folder.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s