Reading file data from shared folder with authentication (FileNotFound Exception) - java

Following is the code I use to access file from a share folde by authenticating and reading data from the file.(using JCIFs)
public void findFiles() throws Exception{
String url = rs.getString("addPolicyBatchFolder_login_url"); //username, url, password are specified in the property file
String username = rs.getString("addPolicyBatchFolder_login_userName");
String password = rs.getString("addPolicyBatchFolder_login_password");
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(null, username, password);
SmbFile dir = null;
dir = new SmbFile(url, auth);
SmbFilenameFilter filter = new SmbFilenameFilter() {
#Override
public boolean accept(SmbFile dir, String name) throws SmbException {
return name.startsWith("starting string of file name");//picking files which has this string on the file name
}
};
for (SmbFile f : dir.listFiles(filter))
{
addPolicyBatch(f.getCanonicalPath()); //passing file path to another method
}
}
With this code, I'm successfully authenticating and I'm able to list the files. And I tried printing canonical path(i tried with just f.path() also) and im able to print the complete path.
Following is the next method.
public void addPolicyBatch(String filename) throws Exception{
File csvFile = new File(filename);
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(csvFile)); //FileNotFound exception
while((line = br.readLine()) != null){
//more code
In the above method, when it comes to bufferReader, its showing FleNotFoundException.
If I print the canonical path, following is the output.
smb://sharePath/file.csv correct path
But in the second method(where I get Exception), the exception is as follows.
java.io.FileNotFoundException: smb:\sharePath\file.csv (The filename, directory name, or volume label syntax is incorrect)
As you can see, there is only one \ after smb:.
I'm not sure why its not passing the exact file path as printed in the first method.

If you remove the leading smb: from the name it should work.
Alternatively, you can change your method as follows and use the smb file to create a reader:
public void addPolicyBatch(SmbFile smbFile) throws Exception {
BufferedReader br = null;
try {
SmbFileInputStream smbStream = new SmbFileInputStream(smbFile);
br = new BufferedReader(new InputStreamReader(smbStream));
String line;
while((line = br.readLine()) != null){
//....
Edit, renaming a file.
If you want to use SmbFile to rename, you need the authentication object
public static void renameSmbFile(SmbFile srcFile, String completeUrl,
NtlmPasswordAuthentication auth) throws Exception {
SmbFile newFile = new SmbFile(completeUrl,auth);
srcFile.renameTo(newFile);
}
Wenn using a File object, that is not neccessary:
public static void renameFile(SmbFile srcFile, String nameWithoutProtocol,
NtlmPasswordAuthentication auth) throws Exception {
String fileName = srcFile.getCanonicalPath();
fileName = fileName.substring(4);//removing smb-protocol
new File(fileName).renameTo(new File(nameWithoutProtocol));
}

Related

Buffered Writer not writing to txt file from ArrayList

I am having a spot of bother getting BufferedWriter to write output to a txt file I have.
When I compile the program, I do not get any errors but the txt file arrives in my project blank.
I have looked on here at similar questions and tried a few of the proposed solutions to resolve it without success, like closing the stream etc
public void storeToDoItemsOntoTxtFile () throws IOException {
Path path = Paths.get(fileName);
BufferedWriter buffyWriter = Files.newBufferedWriter(path);
try {
Iterator<ToDoItem> bigIterator = toDoItems.iterator();
while (bigIterator.hasNext()) {
ToDoItem item = bigIterator.next();
buffyWriter.write(String.format("%s\t%S\t%s", item.getShortDescription(), item.getDetails(), item.getDeadline().format(formatter)));
buffyWriter.newLine();
}
} finally {
if (buffyWriter !=null) {
buffyWriter.close();// when we are done working with the writer
}
}
}
BufferedReader
public void loadToDoItemsFromTxtFile() throws IOException {
toDoItems = FXCollections.observableArrayList();
Path path = Paths.get(fileName);
BufferedReader buffyReader = Files.newBufferedReader(path);
String buffyInput;
try {
while ((buffyInput = buffyReader.readLine()) !=null) {
String [] itemPieces = buffyInput.split("\t");
String shortDescription = itemPieces[0];
String details = itemPieces[1]; //
String dateString = itemPieces [2];
LocalDate date = LocalDate.parse(dateString, formatter);
ToDoItem toDoItem = new ToDoItem(shortDescription,details,date);
toDoItems.add(toDoItem);
}
} finally {
if (buffyReader != null) {// ie the buffy reader states that there is a toDoItem" in the txt file
buffyReader.close();
}
}
}

How can I parse a csv file to apache hbase in a table?

I'm new to Apache Hbase and I need to parse a csv file with values to a table in HBase
The below code is what I have tried:
public class HBaseDataInsert
{
Configuration conf;
HTable hTable;
HBaseScan hbaseScan;
public HBaseDataInsert() throws IOException
{
conf = HBaseConfiguration.create();
hTable = new HTable(conf, "emp_java");
}
public void upload_transactionFile() throws IOException
{
String currentLine = null;
BufferedReader br = new BufferedReader(
new FileReader("transactionsFile.csv"));
while ((currentLine = br.readLine()) != null)
{
System.out.println(currentLine);
String[] line = currentLine.split(",");
Put p = new Put(Bytes.toBytes(line[0] + "_" + line[1]));
p.add(Bytes.toBytes("details"), Bytes.toBytes("Name"), Bytes.toBytes(line[0]));
p.add(Bytes.toBytes("details"), Bytes.toBytes("id"), Bytes.toBytes(line[1]));
p.add(Bytes.toBytes("details"), Bytes.toBytes("DATE"), Bytes.toBytes(line[2]));
p.add(Bytes.toBytes("transaction details"), Bytes.toBytes("TRANSACTION_TYPE"), Bytes.toBytes(line[3]));
hTable.put(p);
}
}
}
I'm getting the following error:
/tmp/java_D5BSep/HBaseDataInsert.java:24: error: reached end of file
while parsing }
You have missed the "}" for your main class. Please add it at the end and check.

Adding a String to a file name and still be able to use it

I have a xml file that I'm getting its full path, and pass it to a function where I add a String to its name. However I'm not being able to use it (the initial fullpath) after adding the string. How can it be done, that after getting the fullpath in search(String dirName), and adding the string in lk(String fullpath), I can still use the path which is returned by search(String dirName).
public String search( String dirName)throws Exception{
String fullPath = null;
File dir = new File(dirName);
if ( dir.isDirectory() )
{
String[] list = dir.list(new FilenameFilter()
{
#Override
public boolean accept(File f, String s )
{
return s.endsWith(".xml");
}
});
if ( list.length > 0 )
{
fullPath = dirName+list[0];
lockFile(fullPath);
return fullPath;
}
}
return "";
}
public void lk( String fullPath) throws Exception {
File f = new File(fullPath);
String fileNameWithExt = f.getName();
try {
File newfile =new File(fileNameWithExt+".lock");
if(f.renameTo(newfile)){
System.out.println("Rename succesful");
}else{
System.out.println("Rename failed");
}
} catch (Exception e) {
e.printStackTrace();
}
}
try this
File originalFile = new File(<file parent path>, "myxmlfile");
File cloneFile = new File(originalFile.getParent(),
originalFile.getName()+"<anything_i_want_to_add>");
Files.copy(originalFile.toPath(),cloneFile.toPath());
//now your new file exist and you can use it
originalFile.delete();//you delete the original file
...
//after you are done with everything and you want the path back
Files.copy(cloneFile.toPath(),originalFile.toPath());
cloneFile.delete();
In your lock method, you are calling renameTo method. Because of that, the original filename is now gone, and is replaced by the new filename that ends with .lock.
The java.io.File class is not a file pointer but an object to hold a filename. Using a file object that still refers to an old filename will cause an error.
To answer your question: If you want the old filename after locking, you must use a different approach in locking your file. For example, MS Access locks their .accdb files by creating a lockfile with the same filename as the opened .accdb file.
You may use this code as a reference:
public boolean fileIsLocked(File file) {
File lock = new File(file.getAbsolutePath() + ".lock");
return lock.exists();
}
public void lockFile(File file) {
if (!fileIsLocked(file)) {
File lock = new File(file.getAbsolutePath() + ".lock");
lock.createNewFile();
lock.deleteOnExit(); // unlocks file on JVM exit
}
}
public void unlockFile(File file) {
if (fileIsLocked(file)) {
File lock = new File(file.getAbsolutePath() + ".lock");
lock.delete();
}
}

Write String into a file, which the user chooses from <input type="file">

I want to write a String to a file, which the user chooses from . I'm unable to do it because I need the fileName and fileLocation to write my String to the file. But the request.getParamater("") gives me just the fileName. I know that it won't return the fileLocation because of security issues. Then, how do I write my String from the file chosen on my jsp. Please advise.
You cannot write to that file directly.
Short answer : Make a copy file on server.
Long answer:
1) Get the file.
2) Save it on server.
3) Append to that file. Do not overwrite.
4) Again send back the file to user with response.
Do some steps
Get file name using getFileName() method. Store it on server side
if some one wants to Save Same file name again then you append Some Date after file Name. so you can easily get all the files without any code changes.
After write String into file close the file and flush .
See i have upload the file form Front End and Store it on Some local system . when you try to upload Same file again then it append Date with File name
public class uploadFile {
private File myFile;
private String myFileContentType;
private String myFileFileName;
private String destPath;
public String upload() throws IOException {
try {
destPath = System.getProperty("user.home") + System.getProperty("file.separator") + "File-Uploads";
File destFile = new File(destPath, myFileFileName);
File file1 = new File(destFile.toString());
boolean b = false;
Date date = new Date();
if (!(file1.exists())) {
b = file1.createNewFile();
}
if (b) {
FileUtils.copyFile(myFile, destFile);
} else {
String fileContent = "";
File f = new File(file1.toString());
FileInputStream inp = new FileInputStream(f);
byte[] bf = new byte[(int) f.length()];
inp.read(bf);
fileContent = new String(bf, "UTF-8");
System.out.println("file===>" + fileContent);
String filename = destFile.toString() + date;
FileWriter fw = new FileWriter(filename, true);
fw.write(fileContent);
fw.close();
FileUtils.copyFile(myFile, destFile);
}
return SUCCESS;
} catch (IOException e) {
return SUCCESS;
}
}
public File getMyFile() {
return myFile;
}
public void setMyFile(File myFile) {
this.myFile = myFile;
}
public String getMyFileContentType() {
return myFileContentType;
}
public void setMyFileContentType(String myFileContentType) {
this.myFileContentType = myFileContentType;
}
public String getMyFileFileName() {
return myFileFileName;
}
public void setMyFileFileName(String myFileFileName) {
this.myFileFileName = myFileFileName;
}
}

File sending Via Java

My code is:
public class RemotePlay {
static final String USER_NAME = "bwisniewski";
static final String PASSWORD = "xxx";
static final String NETWORK_FOLDER = "smb://192.168.1.141/ADMIN$/";
public static void main(String[] args) throws IOException, InterruptedException {
// TODO Auto-generated method stub
String fileContent = "This is a test File";
new RemotePlay().copyFiles(fileContent, "testFile1.txt");
}
public boolean copyFiles(String fileContent, String fileName) {
boolean successful = false;
try{
String user = USER_NAME + ":" + PASSWORD;
System.out.println("User: "+user);
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user);
String path = NETWORK_FOLDER + fileName;
System.out.println("Path: "+path);
SmbFile sFile = new SmbFile(path, auth);
SmbFileOutputStream sfos = new SmbFileOutputStream(sFile);
sfos.write(fileContent.getBytes());
successful = true;
System.out.println("Successful "+successful);
}
catch(Exception e) {
successful = false;
e.printStackTrace();
}
return successful;
}}
How can I change it to send exe file to ADMIN$ share. I prefer to use this method because I have to authenticate to remote pc. If you got better ideas to copy file to ADMIN$ share I am looking forward to hear about it.
Thanks.
sfos.write(fileContent.getBytes());
if your data is text, then why not to use PrintWriter to write down your file
public static void main(String [] args) throws Exception { // temporary
File fileOne = new File("testfile1.txt");
PrintWriter writer = new PrintWriter(fileOne);
// write down data
writer.println("This is a test File");
// free resources
writer.flush();
writer.close();
}
and about the extension, you can use any extension you want while creating the file, it will still hold the data, and can be opened if you renamed it to the correct extension on the hard drive
if you named your file testfile.exe it will still hold your data, but when you double click it it wont work until you rename it to testfile.txt (or it will work if the extension is compatible with the data in the file)

Categories