Write I/O file to shared network drive using credentials - java

I want to drop a .txt file on a shared network drive. The path is a map on a networkdrive which requires credentials (login and password). Can i pass these parameters using FileOutputStream?
FileOutputStream fos;
DataOutputStream dos;
try {
File file= new File(path + "/" + fileName + ".txt");
fos = new FileOutputStream(file);
dos=new DataOutputStream(fos);
dos.writeChars(stringContent);
dos.close();
fos.close();
}
catch(IOException eio){
}
Thank you.

No. Use java CIFS Client library. you can connect remote windows machine through java. example -
String user = "user:password";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user);
String path = "smb://my_machine_name/D/MyDev/test.txt";
SmbFile sFile = new SmbFile(path, auth);
SmbFileOutputStream sfos = new SmbFileOutputStream(sFile);
sfos.write("Test".getBytes());
sfos.close();
Thanks
EDIT: JCIFS only supports the unsecure SMB1 protocol and has been in maintainance mode for some years. Use jcifs-ng for SMB2/SMB3 support which is required from Windows 10.

This code worked for me:
public void downloadFromNetworkDrive3() throws MalformedURLException, SmbException, IOException {
String user = "domain;username:password";//domain name which you connect
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user);
String path = "smb://198.168.20.27/D$/MICROS/opera/export/OPERA/dinaamum/audit/Thumbs.db";
SmbFile sFile = new SmbFile(path, auth);
SmbFileOutputStream sfos;
SmbFileInputStream sfis;
try {
// sfos = new SmbFileOutputStream(sFile);
sfis = new SmbFileInputStream(sFile);
// sfos.write("hihowareyou".getBytes());
File tempFile = null;
String filePath = null;
filePath = "c://usr/local/cache/leelafiles";
tempFile = new File(filePath);
if (tempFile.exists()) {
} else {
tempFile.mkdirs();
}
tempFile = new File(filePath);
// File[] allFilesAndDirs = tempFile.listFiles();
FileOutputStream writer = new FileOutputStream(tempFile + File.separator + "Thumbs.db");
byte[] b = new byte[8192];
int n;
while ((n = sfis.read(b)) > 0) {
System.out.write(b, 0, n);
writer.write(b, 0, n);
}
sfis.close();
writer.close();
} catch (UnknownHostException ex) {
Logger.getLogger(ReportSchedulerJob.class.getName()).log(Level.SEVERE, null, ex);
}
}

Related

unable to download file from java

I had written a program to get stocks data from yahoo finance website, my code used to work previously, lately it has stopped working.
When i access the same url from browser a file is downloaded,
however from java code i get and empty stream
here is sample link
These are the codes that i have tried
try{
ReadableByteChannel rbc = Channels
.newChannel(website.openStream());
FileOutputStream fos;
fos = new FileOutputStream(Type+"//"+
FileName + ".csv");
fos.getChannel().transferFrom(rbc, 0,
Long.MAX_VALUE);
fos.flush();
fos.close();
String fileName = "file.txt"; //The file that will be saved on your computer
URL link = new URL(website.toString());
//Code to download
InputStream in = new BufferedInputStream(link.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(response);
fos.close();
//End download code
Runnable r1 = new Analyzer(Type+"//"+
FileName + ".csv",Type,Name);
Thread r2= new Thread(r1);
r2.start();
r2.join();
}
catch(Exception e)
{
e.getMessage();
}

Java application open and play media error on Debian

I am currently working on an application and I wrote it with Java. It is downloading some media files to local computer and open it with a Java method called Desktop.getDesktop().open(file); It is working good on windows but it is not working on debian.
Here is used download from url method:
public String DownloadFromUrlAndGetPath(String DownloadUrl) {
String fileName="";
try {
URL url = new URL(DownloadUrl);
URLConnection ucon = url.openConnection();
String raw = ucon.getHeaderField("Content-Disposition");
// raw = "attachment; filename=abc.mp3"
if(raw != null && raw.indexOf("=") != -1) {
fileName = raw.split("=")[1]; //getting value after '='
fileName = fileName.replace("\"", "").trim();
} else {
return "";
}
File file = new File(Paths.get(System.getProperty("user.home"), "MyFolderToSaveFiles") +"/"+ fileName);
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
while ((current = bis.read()) != -1) {
try {
baf.append((int)((byte)current));
continue;
}
catch (Exception var12_13) {
}
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
}
catch (IOException e) {
e.getMessage();
}
}
return Paths.get(System.getProperty("user.home"), "MyFolderToSaveFiles") +"/"+ fileName;
Then I want to open that file like that:
File f = new File(url);
Desktop.getDesktop().open(f);
And the error says;
Any suggestion ? Thanks
I solved that with using this , so when I open file I am using xdg-open..

can I download file from ftp without save it my directory first

I have a page download, where the file you want to download must be downloaded first from other server use ftp.
i use this code to download from ftp:
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
String remoteFile1 = "/Users/A/file.txt";
File downloadFile1 = new File("/Users/B/Downloads/file.txt");
OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1));
boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1);
outputStream1.close();
if i use this program, i need to save file.txt in my directory /Users/B/Downloads/ then i need to use my other code to download file.txt from /Users/B/Downloads/.
is it possible if i download the file.txt without save it first in my directory /Users/B/Downloads/?
You could use ByteArrayOutputStream instead of BufferedOutputStream.
ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();
boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1);
String fileContent = outputStream1.toString("UTF-8");
To write to a stream, in memory, use: ByteArrayOutputStream
new ByteArrayOutputStream();
Another Way:
BufferedReader reader = null;
String remoteFile1 = "/Users/A/file.txt";
try {
InputStream stream = ftpClient.retrieveFileStream(remoteFile1);
reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
int data;
while ((data = reader.read()) != -1) {
//here, do what ever you want
}
} finally {
if (reader != null) try { reader.close(); } catch (IOException ex) {}
}

Java IO Server Client read and process users input

I have a simple Fileserver and Client (code from the web) that let me send files to my other laptop inside my home LAN. Now, the file sent from the server to the client is hardcoded but i want to prompt user at client-side to input a filename, send it to the server and send back the specified file. My code looks like this:
Server
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) {
BufferedOutputStream outputStream;
BufferedInputStream inputStream;
FileInputStream fileInput;
String file = "C:/java/file.mp4";
try {
ServerSocket socket = new ServerSocket(12345);
while(true) {
Socket clientSocket = socket.accept();
outputStream = new BufferedOutputStream(clientSocket.getOutputStream());
fileInput = new FileInputStream(file);
inputStream = new BufferedInputStream(fileInput);
int packetToSend = -1;
byte[] buffer = new byte[8192];
while((packetToSend = inputStream.read(buffer)) > -1) {
outputStream.write(buffer, 0, packetToSend);
System.out.println("sending " + packetToSend + " bytes");
outputStream.flush();
}
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
And thats the Client Code (IPAdress of the Server is argument s[0] and the path to save the file is s[1] in main method.
import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] s) {
try {
String address = new String(s[0]);
String fileToSave = new String(s[1]);
Socket socket = new Socket(address,12345);
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
FileOutputStream fos = new FileOutputStream(fileToSave);
int n;
byte[] buffer = new byte[8192];
System.out.println("Connected");
while ((n = bis.read(buffer)) > 0) {
System.out.println("received "+n+" bytes");
fos.write(buffer, 0, n);
fos.flush();
}
System.out.println("recieved");
}
catch(Exception e) {
e.printStackTrace();
}
}
}
I want to promt the user on client side to input a filename after client is connected to send to the server and the server should send that file.
i tried to put this in client side after System.out.println("connected");
System.out.print("Insert filename to download: ");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String input = null;
try {
input = reader.readLine();
} catch (IOException ioe) {
System.out.println("Eingabe konnte nicht verarbeitet werden!");
System.exit(1);
}
System.out.println("Eingabe: " + input);
and on server side i put this after outputStream = new BufferedOutputStream(clientSocket.getOutputStream()); to override the hardcoded filename at the beginning of server class.
inputStream = new BufferedInputStream(clientSocket.getInputStream());
fileInputStream = new FileInputStream(inputStream);
fileInputStream = new BufferedInputStream(fileInput);
Once a connection is established, client side is idle (cant input something) and server side does nothing after writing out to console "new connection".
how can i solve this please?
The client sends to the server the filename. So first you must extract the filename from the socket's input stream. To do that you need to establish a protocol for how information will be sent. This is critical when dealing with TCP streams, which is different from UDP datagrams. Typically two newlines is used to convey the end of a message. But because it is not normal for a filename to have a newline in it, we will use one newline to convey end of message.
We can then use Scanner to extract the filename from the client's socket.
String fileName;
Scanner scanner = new Scanner (clientSocket.getInputStream());
while(scanner.hasNextLine())
{
fileName = scanner.nextLine();
break;
}
fileInputStream = new FileInputStream(fileName);
fileInputStream = new BufferedInputStream(fileInput);
In this example the fileName must be the absolute path to that file as its sits in the server's file system. In future versions you might want to use a directory on the server where files are stored and the client can give you the relative path to file from that directory. Here is how that would look like.
String fileName;
Scanner scanner = new Scanner (clientSocket.getInputStream());
while(scanner.hasNextLine())
{
fileName = scanner.nextLine();
break;
}
fileInputStream = new FileInputStream(FILE_DIR + fileName);
fileInputStream = new BufferedInputStream(fileInput);
The variable FILE_DIR would look something like:
static String FILE_DIR = "C:/java/";
And the file that the client would send over would just be file.mp4
EDIT 1:
Here is the Client code with the recommendations. Please note that this test quality code, not production code.
import java.net.*;
import java.io.*;
public class Client {
static String FILE_DIR = "./";
public static void main(String[] s) throws IOException {
/**
* Establish socket using main args.
*/
String address = s[0];
while (true) {
/**
* Get the file name from the user.
*/
System.out.print("Insert filename to download: ");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String fileName = null;
try {
fileName = reader.readLine();
} catch (IOException ioe) {
System.out.println("Eingabe konnte nicht verarbeitet werden!");
System.exit(1);
}
System.out.println("Eingabe: " + fileName);
/**
* Create the socket.
*/
Socket socket = new Socket(address, 12345);
/**
* With file name in hand, proceed to send the filename to the
* server.
*/
//...put in try-with-resources to close the outputstream.
try (BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream())) {
System.out.println("Connected: Sending file name to server.");
//...send file name plus a newline.
bos.write((fileName + '\n').getBytes());
bos.flush();
/**
* Get the file contents and save to disk.
*/
//...wrap input stream in DataInpuStream for portability.
//...put in try-with-resource to close the input stream.
try (BufferedInputStream bis = new BufferedInputStream(new DataInputStream(socket.getInputStream()))) {
DataOutputStream fos = new DataOutputStream(new FileOutputStream(fileName));
int n;
byte[] buffer = new byte[8192];
System.out.println("Connected: Recieving file contents from server.");
while ((n = bis.read(buffer)) > 0) {
System.out.println("received " + n + " bytes");
fos.write(buffer, 0, n);
fos.flush();
}
System.out.println("recieved");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
and here's the server code. Please note the server is retrieving the file from local directory called ./files/, please change that to whatever directory you want.
import java.net.;
import java.io.;
import java.util.Scanner;
public class Server {
static String FILE_DIR = "./files/";
public static void main(String[] args) {
BufferedInputStream inputStream;
FileInputStream fileInput;
try {
ServerSocket socket = new ServerSocket(12345);
while (true) {
Socket clientSocket = socket.accept();
/**
* Get the file name from the client. File name is one per line.
*/
//...put in trye-with-resources to close InputStream for us.
try (InputStream inputFromClient = clientSocket.getInputStream()) {
System.out.println("Connected: Getting file name from client.");
Scanner scanner = new Scanner(inputFromClient);
String fileName;
if (scanner.hasNextLine()) {
fileName = scanner.nextLine();
System.out.println("File name = " + fileName);
} else {
//...no line found, continue. consider logging an error or warning.
continue;
}
/**
* With fileName in hand, we can proceed to send the
* contents of the file to the client.
*/
fileInput = new FileInputStream(fileName);
//...use DataInputStream for more portable code
DataInputStream dataInput = new DataInputStream(fileInput);
inputStream = new BufferedInputStream(dataInput);
int packetToSend = -1;
byte[] buffer = new byte[8192];
//...consider closing the OutputStream to let the client know.
//...use try-with-resource to close the outputStream for us.
//...wrap your outputStream in DataOutputStream
try (BufferedOutputStream outputStream = new BufferedOutputStream(new DataOutputStream(clientSocket.getOutputStream()))) {
while ((packetToSend = inputStream.read(buffer)) > -1) {
outputStream.write(buffer, 0, packetToSend);
System.out.println("sending " + packetToSend + " bytes");
outputStream.flush();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

writing into file in a client and NegativeArraySizeException

i have a server which sending thousands of tiny files like below:
static File file = null;
static File temp = null;
private static ServerSocket serverSocket;
private static Socket socket;
public static void main(String[] args) throws FileNotFoundException, IOException
{
serverSocket = new ServerSocket(3000);
socket = serverSocket.accept();
System.out.println("Connected");
File folder = new File("C:...\\Desktop\\thousands_of_tiny_files");
File[] listOfFiles = folder.listFiles();
File result[]=new File[listOfFiles.length];
byte [] bytearray = null;
FileInputStream fin =null;
BufferedInputStream bin = null;
for(int j=0;j<listOfFiles.length;j++){
String path= listOfFiles[j].getPath();
result=sendFile(path);
for(int i=0;i<result.length;i++)
{
fin = new FileInputStream(result[i]);
bin = new BufferedInputStream(fin);
bytearray = new byte [(int)result.length];
bin.read(bytearray,0,bytearray.length);
OutputStream os = socket.getOutputStream();
System.out.println("Sending Files "+ result[i]);
os.write(bytearray,0,bytearray.length);
os.flush();
System.out.println("File transfer completed");
}
}
fin.close();
bin.close();
socket.close();
}
public static File[] sendFile(String path)
{
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
File[] resultt = new File[listOfFiles.length];
for(int i=0;i<listOfFiles.length;i++)
{
temp=listOfFiles[i];
if(temp.isFile() && temp!=null)
resultt[i]=temp;
}
return resultt;
}
it is successfull but my problem is in client side. i dont know how to distinguish between the files and write them seperately into the client.
EDIT2:
I changed the server side code like following using ZipOutputStream but still dont know how to unzip and write it in the client (mostly, dont know how to define the FileOutputStream in client:
for(int i=0;i<result.length;i++)
{
fin = new FileInputStream(result[i]);
bytearray = new byte [(int)result.length];
ZipOutputStream zipOpStream = new ZipOutputStream(socket.getOutputStream());
zipOpStream.putNextEntry(new ZipEntry(result[i].getName()));
System.out.println("Sending Files "+ result[i]);
zipOpStream.write(bytearray,0,bytearray.length);
zipOpStream.flush();
System.out.println("File transfer completed");
}
}
socket.close();
}
and the reciever code:
socket = new Socket("127.0.0.1",3000);
String outDir = "C:...\\Desktop\\here";
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
ZipInputStream zips = new ZipInputStream(bis);
ZipEntry zipEntry = null;
while(null != (zipEntry = zips.getNextEntry())){
String fileName = zipEntry.getName();
File outFile = new File(outDir + "/" + fileName);
System.out.println("----["+outFile.getName()+"], filesize["+zipEntry.getCompressedSize()+"]");
if(zipEntry.isDirectory()){
File zipEntryFolder = new File(zipEntry.getName());
if(zipEntryFolder.exists() == false){
outFile.mkdirs();
}
continue;
}else{
File parentFolder = outFile.getParentFile();
if(parentFolder.exists() == false){
parentFolder.mkdirs();
}
}
System.out.println("ZipEntry::"+zipEntry.getCompressedSize());
FileOutputStream fos = new FileOutputStream(outFile);
int fileLength = (int)zipEntry.getSize();
byte[] fileByte = new byte[fileLength];
zips.read(fileByte);
fos.write(fileByte);
fos.close();
socket.close();
}
now i get an exceptiom"negative NegativeArraySizeException"
Exception in thread "main" java.lang.NegativeArraySizeException
at recieve.Reciever.<init>(Reciever.java:71)
at recieve.Recieve$1.<init>(Recieve.java:28)
at recieve.Recieve.main(Recieve.java:28)
ZipEntry::-1
which probably is because of
int fileLength = (int)zipEntry.getSize();
but how can I solve this? i need the siz of next entry of zip folder for writing into the file.
but the size is in Long not int
How about writing it into a ZipOutputStream where you can receive the file on the other side as a single stream. Once you have the entire output, you can write the reverse code to deflate the zip file and get all the files. Providing a sample code for writing the Zip into your socket stream, you can build your code over this.
Refer this length for a sample Server and Client implementation sending the file using a ZipOutputStream Stick2Code

Categories