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.
2 responses so far ↓
John // September 9, 2008 at 2:12 pm |
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.
Mr. President // September 10, 2008 at 4:07 am |
That’s right. The remote machine you are accessing would need to provide you appropriate access rights (read/write) to the specific folder.