Error while Rename file in ftp folder Java - java

Following is my code to read the file and rename it afterwards. Im using apache commons.net 3.0.1.
client.connect(localhost);
boolean login = client.login("username", "password");
if(login){
System.out.println("login successful");
boolean chdir = client.changeWorkingDirectory("/home/folder1/child/");
String url = client.printWorkingDirectory(); // EDIT
FTPFile[] result = client.listFiles(url, filter);
if (result != null && result.length > 0) {
for (FTPFile aFile : result) {
try{
String filename = aFile.getName();
InputStream is= client.retrieveFileStream(filename);
br = new BufferedReader(new InputStreamReader(is));
while((line = br.readLine()) != null){
System.out.println("the line is"+line);
}
}
finally{
if(br!=null){
try{
br.close();
String oldFilename =url + "/" +aFile.getName();
String newFilename = "PRO"+aFile.getName();
boolean rename = client.rename(oldFilename, newFilename);
if(rename){
System.out.println("renamed");
}
else{
System.out.println("Error in renaming");
}
}
The file deosn't get renamed and the program prints
error in renaming files (cz boolean rename = false).
I have refereed to different examples. But all seems to show the same problem.
The file is picked after filter and read without any issues.
If anyone could point to what I'm doing wrong here, that'd be very helpful.
Here, the url is String url = client.printWorkingDirectory();
I have tried with both relative path and absolute path. And giving full path only to the oldFilename and just the filname to the newFilename. Both did not work.
EDIT
Before changing the directory, the url will be / which is root.
After changing the directory, the url will be /home/folder1/child/. This is the where the files exists.

InputStream retrieveFileStream(String remote):This method returns an InputStream which we can use to read bytes from the remote file. This method gives us more control on how to read and write the data. But there are two important points when using this method:
The method completePendingCommand() must be called afterward to finalize file transfer and check its return value to verify if the download is actually done successfully.
boolean success = ftpclient.completePendingCommand();
if (success){
System.out.println("File #2 has been downloaded successfully.");
}
We must close the InputStream explicitly.
is.close(); //is = InputStream
SOURCE

Related

How to rename a txt file using Java after copying contents from another txt file

I have created a program where there is a file called groups.txt. This file contains a list of names. To delete a group, it has to exist within the file. I used the Scanner method to search through each line for the name. If it contains the line, it sets val as 1. Which triggers the val == 1 condition. What I wanted to do during this block, is try to delete groupName from the groups.txt file. To do this, I created a new txt file called TempFile which copies all the names from groups.txt EXCEPT groupName. This file is then renamed to groups.txt and the old groups.txt file is deleted.
Everything works as intended, except the renaming. The temp.txt file still exists and the groups.txt file is unchanged. I checked the boolean success, and it always returns as false. Any ideas how to solve this?
if (method.equals("delete group")){
int val = 0;
String groupName = myClient.readLine();
try {
Scanner file = new Scanner(new File("groups.txt"));
while (file.hasNextLine()){
String line = file.nextLine();
if (line.indexOf(groupName) != -1){
val = 1;
}
}
if (val == 1){
try {
File groupFile = new File("groups.txt");
File tempFile = new File("temp.txt");
BufferedReader reader = new BufferedReader(new FileReader(groupFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
System.out.println(groupName);
while ((currentLine = reader.readLine()) != null){
String trimLine = currentLine.trim();
if (trimLine.equals(groupName)){
continue;
} else {
writer.write(currentLine + System.getProperty("line.separator"));
}
}
writer.close();
reader.close();
groupFile.delete();
boolean success = tempFile.renameTo("groups.txt");
} catch (IOException f){
System.err.println("File Not Found: " + f.getMessage());
} }
} catch (FileNotFoundException f){
System.err.println("File Not Found Exception: " + f.getMessage());
}
}
CODE BEFORE THE ABOVE:
if (command.equals("group")){
String method = myClient.readLine();
if (method.equals("create group")){
String groupName = myClient.readLine();
int val = 0;
try {
Scanner file = new Scanner(new File("groups.txt"));
while (file.hasNextLine()){
String line = file.nextLine();
if (line.indexOf(groupName) != -1){
Report.error("group name already exists, please pick another");
val = 1;
}
}
} catch (FileNotFoundException f){
System.err.println("File Not Found: " + f.getMessage());
}
if (val == 0){
try {
PrintWriter out = new PrintWriter(new FileWriter("groups.txt", true));
out.println(groupName);
out.close();
} catch (IOException e){
Report.error("IOException: " + e.getMessage());
}
}
In the second part of the code, this is where I originally update the groups.txt file. So every time the user adds a group, it updates the groups.txt file by adding the new groupName to the end of the file. First, I make sure the groupName doesn't already exist using Scanner. myClient is a BufferedReader which reads from another class which stores what the user types in the command line.
Also do not forget to close Scanner. First you should make delete() work and make sure you know your current working directory, and write your filepath relative to it. Check with:
File file = new File("abc.txt");
System.out.println(file.getAbsolutePath());
One thing might be unrelated, also check your environment because
In the Unix'esque O/S's you cannot renameTo() across file systems. This behavior is different than the Unix "mv" command. When crossing file systems mv does a copy and delete which is what you'll have to do if this is the case. The same thing would happen on Windows if you tried to renameTo a different drive, i.e. C: -> D:

New Created File Can't Open in Java

My else if block will verify the result from remote service.
If the result matches, it will trigger another API call to contact the remote service again. The remote service will send back a file to my client program.
I tested all my code and it is working but I am not able to open back the new file and it's showing the file was corrupted. My client program will read the file from the remote service and write it into another file name in a different directory.
This is my source code:
else if (result == 1 && value.equals("problem"))
{
String Url = "http://server_name:port/anything/anything/";
String DURL = Url.concat(iD);
System.out.println("URL is : " + DURL); // the remote API URL
URL theUrl = new URL (DURL);
HttpURLConnection con1 = (HttpURLConnection) theUrl.openConnection(); //API call
con1.setRequestMethod("GET");
con1.connect();
int responseCode = con1.getResponseCode();
if(responseCode == 200)
{
try
{
InputStream is1 = con1.getInputStream();
BufferedReader read1 = new BufferedReader (new InputStreamReader(is1));
String data1 = "" ;
while ((data1 = read1.readLine()) != null)
{
PrintStream ps = new PrintStream(new FileOutputStream(filePath));
ps.print(data1);
ps.close();
}
System.out.println("The new sanitized file is ready");
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
This is my filePath mentioned in the code D:/file/red_new.docx. This is how I get my file path: String filePath = "D:/file/"+fn+"_new."+fileType;. The fn variable is the filename from the JSON string from the first API call while the fileType is the file type from the JSON string from the second API call. I add in the _new to indicate it's a new file and using java concatenate with the fn and fileType to obtain the full path.
You're creating a new output file per line of input, so you'll only ever get the last line. And you're also losing the line terminators. Try this:
PrintStream ps = new PrintStream(new FileOutputStream(filePath));
while ((data1 = read1.readLine()) != null)
{
ps.println(data1);
}
ps.close();
You're also not closing the input stream.
If these files aren't all known to be text files you should be using InputStream and OutputStream.
Please use finally block to close the open streams. If stream is not closed, you can't open it until the process holding the stream is closed or released.
eg:
try( InputStream is1 = con1.getInputStream()){
// ...
}

AndroidStudio can't find CSV file. Tried Absolute File Path & Relative File Path

I've created a simple Android app that displays text to the user.
Now I'm attempting to implement a CSVReader to retrieve text from a CSV file. After hours of trying different things.
I finally implemented an open source CSVReader (At least it's not giving me any compile errors anymore).
Now when I run the app, it crashes and I get a "file not found" exception. Either I'm not placing my CSV file in the correct location, I'm not referencing the correct file path, or both.
I've tried using the absolute file path (ex. starting with my C:/Users/Tim/AndroidStudioProjects/...).
I've also tried using a relative path starting with the Assets folder (ex. "Assets/SOCIAL_POSTS.csv") and nothing I've tried has worked.
I've tried looking for similar Questions on Stack Overflow, and I've tried several variations of file paths and nothing has worked so far. What do you think I should try next?
Here is a link to this project on GitHub.
The code pointing to the CSV file is under
app > src > main > java > com > example > tim > inspiredquestions
The CSV file is called SOCIAL_POSTS.csv and it is under
Assets > SOCIAL_POSTS.csv
Final note: I've used StackOverflow for debugging help for a year now, but this is the first question I've asked.
Thank-you for your patience! I'm trying to be as self-reliant as I can, but I'm going on a limb and asking for help. I'm sure this problem has a simple answer I'm overlooking.
I finally figured out the answer. I added
final CSVReader csvReader = new CSVReader(new InputStreamReader(c.getAssets().open("SOCIAL_POSTS.csv") to my load function in Game.java after looking at the answer to this question. Previously I had put my CSV file in an assets folder under app/src/main but I didn't know how to access the file properly until reviewing that SO post.
How I use Android Studio for files is to position my files in the raw folder, then push them to the /data/data/yourapplication/files directory. I do this through Tools/Android/Android Device Monitor and navigate to the /data/data/yourapplication/files directory and select an icon in the upper right that says "Push a file onto the device", then navigate to the raw files in my app and select the csv file(s) I want placed in the /files directory.
From that point I aim my stream readers at that directory,
in my case, /data/data/app/com.android/example/darrell/MenuPlanner/files Directory. Files addressed here use the file extension and do not need the path specified:
public List<EntreeData> ReadEntreesFromFilesDir(Context inContext) {
this.mContext = inContext;
List<String> lines = new ArrayList<String>();
String[] separated;
try {
FileInputStream fis = mContext.openFileInput("entrees.csv");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
while ((mLine = bufferedReader.readLine()) != null) {
if (mLine == null) break;
lines.add(mLine);
}
fis.close();
isr.close();
} catch (FileNotFoundException e) {
Log.d("FILE ERROR", e.getMessage() + " not found");
} catch (IOException ioe) {
Log.d("FILE ERROR", ioe.getMessage());
}
for (int x = 0;x<lines.size();x++){
separated = lines.get(x).split(",");
EntreeData thisEntree = new EntreeData();
thisEntree.setEntreeName(separated[0].trim());
thisEntree.setCategory(separated[1].trim());
thisEntree.setSubcategory(separated[2].trim());
thisEntree.setRecipe(separated[3].trim());
mEntreeList.add(thisEntree);
}
return mEntreeList;
}
As a fallback I read from /res/raw directory which is not writeable and I am assured of file integrety. Files here do not use an extension, so point your stream reader at a file without using the extension name.
Also use the asset manager to access these files:
public List<EntreeData> ReadEntreesFileFromRaw(Context inContext) {
this.mContext = inContext;
List<String> lines = new ArrayList<String>();
String[] separated;
AssetManager assetManager = mContext.getAssets();
try {
InputStream inputStream = mContext.getResources().openRawResource(R.raw.entrees);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
int lineCount = 0;
while ((mLine = reader.readLine()) != null) {
separated = mLine.split(",");
EntreeData entreeEntry = new EntreeData();
if (mLine == null) break;
separated = mLine.split(",");
entreeEntry.setEntreeName(separated[0].trim());
entreeEntry.setCategory(separated[1].trim());
entreeEntry.setSubcategory(separated[2].trim());
entreeEntry.setRecipe(separated[3].trim());
mEntreeList.add(lineCount, entreeEntry);
lineCount++;
}
inputStream.close();
} catch (FileNotFoundException e) {
Log.d("FILE ERROR", e.getMessage() + " not found");
} catch (IOException ioe) {
Log.d("FILE ERROR", ioe.getMessage());
}
return mEntreeList;
}
Good luck and happy programming!

Main.class.getResource() and jTextArea

When I read a file from the jar file and want to put it in in a jTextArea, it shows me crypted symbols, not the true content.
What I am doing:
public File loadReadme() {
URL url = Main.class.getResource("/readme.txt");
File file = null;
try {
JarURLConnection connection = (JarURLConnection) url
.openConnection();
file = new File(connection.getJarFileURL().toURI());
if (file.exists()) {
this.readme = file;
System.out.println("all ok!");
}
} catch (Exception e) {
System.out.println("not ok");
}
return file;
}
And then i read the file:
public ArrayList<String> readFileToArray(File file) {
ArrayList<String> array = new ArrayList<String>();
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(file));
while ((sCurrentLine = br.readLine()) != null) {
String test = sCurrentLine;
array.add(test);
}
} catch (IOException e) {
System.out.println("not diese!");
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
}
}
return array;
}
Now, i put all lines from the ArrayList in the jTextArea, that showes me things like that:
PK����?����^��S?��3��� z_��
%�Q Tl?7��+�;�
�fK� �N��:k�����]�Xk,������U"�����q��\����%�Q#4x�|[���o� S{��:�aG�*s g�'.}���n�X����5��q���hpu�H���W�9���h2��Q����#���#7(�#����F!��~��?����j�?\xA�/�Rr.�v�l�PK�bv�=
The textfiled contains:
SELECTION:
----------
By clicking the CTRL Key and the left mouse button you go in the selection mode.
Now, by moving the mouse, you paint a rectangle on the map.
DOWNLOAD:
---------
By clicking on the download button, you start the download.
The default location for the tiles to download is: <your home>
I am sure that the file exists!
Does anyone know what the problem is? Is my "getResource" correct?
Based on the output, I'm suspecting your code actually reads the JAR file itself (since it starts with PK). Why not use the following code to read the text file:
Main.class.getResourceAsStream("/readme.txt")
That would give you an InputStream to the text file without doing the hassle of opening the JAR file, etc.
You can then pass the InputStream object to the readFileToArray method (instead of the File object) and use
br = new BufferedReader(new InputStreamReader(inputStream));
The rest of your code should not need any change.
This seems to be an encoding problem. FileReader doesn't allow you to specify that. Try using
br = new BufferedReader(new InputStreamReader(new FileInputStream(file), yourEncoding));
You seem to be making far too much work for yourself here. You start by calling getResource, which gives you a URL to the readme.txt entry inside your JAR file, but then you take that URL, determine the JAR file that it is pointing inside, then open that JAR file with a FileInputStream and read the whole JAR file.
You can instead simply call .openStream() on the original URL that getResource returned, and this will give you an InputStream from which you can read the content of readme.txt
br = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
(if readme.txt is not encoded in UTF-8 then change that parameter as appropriate)

read file in an applet

Hi there I want to read out a file that lies on the server.
I get the path to the file by a parameter
<PARAM name=fileToRead value="http://someserver.de/file.txt">
when I now start the applet following error occurs
Caused by: java.lang.IllegalArgumentException: URI scheme is not "file"
Can someone give me a hint?
BufferedReader file;
String strFile = new String(getParameter("fileToRead"));
URL url = new URL(strFile);
URI uri = url.toURI();
try {
File theFile = new File(uri);
file = new BufferedReader(new FileReader(new File(uri)));
String input = "";
while ((input = file.readLine()) != null) {
words.add(input);
}
} catch (IOException ex) {
Logger.getLogger(Hedgeman.class.getName()).log(Level.SEVERE, null, ex);
}
File theFile = new File(uri);
is not the correct method. You accessing an URL, not a File.
Your code should look like this:
try
{
URL url = new URL(strFile);
InputStream in = url.openStream();
(... read file...)
in.close();
} catch(IOException err)
{
(... process error...)
}
You are trying open as a file, something which doesn't follow the file:// uri, as the error suggests.
If you want to use a URL, I suggest you just use url.openStream() which should be simpler.
You will need to sign the applet unless the file is being accessed from the same server/port that the applet came from.

Categories

Resources