Reputation: 10584
How do I iterate through a directory to read *.csv files and upload them in my system in Java?
Ignore the upload part of post.
Upvotes: 0
Views: 2750
Reputation: 40318
Check the File API. Specifically, the File.list* methods; those will list the files in a directory.
Upvotes: 0
Reputation: 5398
You can do something like this to locate all the files in your directory that have a .csv
extension.
File[] files = new File(DIR_LOCATION).listFiles(new FileFilter() {
public boolean accept(File file) {
return file.getName().endsWith(".csv");
}
});
Take a look at the File I/O section of the java tutorial
Upvotes: 2
Reputation: 27482
File.list() will get you all the files in a given directory. File.list() returns it as an array of Strings; File.listFiles() returns it as an array of File objects.
You can then loop through the array and pick out all the ones that end in ".csv".
If you want to be a little more sophisticated, create a FilenameFilter that only passes csv files.
Upvotes: 0
Reputation: 1108802
You can use File#listFiles()
in combination with FilenameFilter
to obtain CSV files of a given directory.
File directory = new File("/path/to/your/dir");
File[] csvFiles = directory.listFiles(new FilenameFilter() {
@Override public boolean accept(File dir, String name) {
return name.endsWith(".csv");
}
});
The remnant of the answer depends on how and where you'd like to upload it to. If it's a FTP service, then you'd like to use Apache Commons Net FTPClient. If it's a HTTP service, then you'd like to use Apache HttpComponents Client HttpClient. If you edit your question to clarify the functional requirement, then I may update this answer to include more detail. You should however be aware that you need some sort of a server on the other side to be able to connect and send/upload the file to. E.g. a FTP or HTTP (web) server.
Upvotes: 1
Reputation: 17472
Give more specifics. Are you talking about a web application or a standalone application. Simple answer is if it is a web application you can't do that as you can upload only files using file control. If its a standalone app, you can read the dir using list
method of file and check if the extension is csv and read it.
Upvotes: 1
Reputation: 9781
Read Sun's tutorial on this:
http://download-llnw.oracle.com/javase/tutorial/essential/io/dirs.html
Upvotes: 0