How to upload multiple files using Swings Applications? - java

I m trying to upload multiple files in swings applications.I have declared an array to hold the values of selected files but when i click on upload button only 1 file is getting uploaded. How can i upload all selected files into database?
The code to Open and Upload File is ....
public void openFile()
{
JFileChooser jfc = new JFileChooser();
jfc.setMultiSelectionEnabled(true);// added line
int result = jfc.showOpenDialog(this);
if(result == JFileChooser.CANCEL_OPTION) return;
try {
ArrayList<String> FileData = new ArrayList<String>();
File[] file = jfc.getSelectedFiles();
String s=""; int c=0;
for(int i=0;i<file.length;i++) //added
{
jep.setText(file[i].toString()); // added
}
return FileData;
}
catch (Exception e)
{
JOptionPane.showMessageDialog(this,e.getMessage(),
"File error",JOptionPane.ERROR_MESSAGE);
}
}

You haven't clearly defined what you actually mean by "upload multiple files". I'm presuming that you wish to load the contents of multiple text files one after the other into a single JEditorPane. If that is the case, Romain's answer shows you an example of loading a single file.
What your code is actually doing though is looping through the array of File objects and setting their path (that is what toString returns on File) as the text within your editor pane. Each one is overriding the last, so that is why you end up with a single file path.
I might also suggest when you pop up your JFileChooser you limit the files a user can select to specific file types (e.g. txt, html).

// get list of selected files
File[] file = jfc.getSelectedFiles();
String s=""; int c=0;
for(int i=0;i<file.length;i++) //added
{
// The toString will just return you back the path of the file object times the number of bytes in the file.
jep.setText(file[i].toString()); // added
}
return FileData;
This code will not work. If you want a method to read a file given a file name into an array of Strings then you will need:
/**
* Read entire contents of a text file.
*
* #param fileName Text file name
* #return ArrayList of String (line) elements
* #throws FileNotFoundException
* #throws IOException
*/
public static ArrayList readTextFile( String fileName )
throws FileNotFoundException, IOException
{
ArrayList lines = new ArrayList();
BufferedReader in = null;
try
{
in = new BufferedReader( new FileReader( fileName ));
String line;
while ( ( line = in.readLine()) != null )
{
lines.add( line );
}
}
finally
{
if ( in != null )
{
try
{
in.close();
}
catch ( IOException ex )
{
}
}
}
return lines;
}
Since you want to read in the contents of several file, just do this in a loop and do each one individually. If you load it all in memory you might run into problems.

Related

is there a way to use the file path instead of file name in BufferedReader?

I would like to add the path instead of the file name in BufferedReader?
I want to use the path because I want the code to pickup any file that has the name "audit" in that specific folder.
So I am currently using this method below, but it only works when I add the absolute path.
`
public static void main(String[] args)
throws IOException {
List<String> stngFile = new ArrayList<String>();
BufferedReader bfredr = new BufferedReader(new FileReader
("file path"));
String text = bfredr.readLine();
while (text != null) {
stngFile.add(text);
text = bfredr.readLine();
}
bfredr.close();
String[] array = stngFile.toArray(new String[0]);
Arrays.toString(array);
for (String eachstring : array) {
System.out.println(eachstring);
}
}
`
I am new to programming any help is much appreciated. Thanks in advance.
FileReader also has a constructor that takes a file. You can create a file object using a URI or a string for the path. You could use a FileFilter or just check if each file matches the name you provide, which is how i would do it:
To get all files in a folder you can use folder.listFiles().
You can then use file.getName().contains("audit") to check if the filename contains "audit".
Note that this is case sensitive, to ignore case you would just use file.getName().toLowerCase().contains("audit") (make sure the string you check here, in this case "audit", is always lower case).
As pointed out by g00se, you will also have to check if file is actually a file and not a directory using file.isFile()
Then in a loop you just read out to content of each file that matches the above condition seperately.
If you need the files in all the subfolders aswell, see this post.
Example:
public static void main(String[] args) throws IOException {
File folder = new File("C:\\MyFolder"); // the folder containing all the files you are looking for
for (File file : folder.listFiles()) { // loop through each file in that folder
if (file.getName().contains("audit") && file.isFile()) { // check if it contains audit in its name
// your previous code for reading out the file content
BufferedReader bfredr = new BufferedReader(new FileReader(file));
List<String> stngFile = new ArrayList<String>();
String text = bfredr.readLine();
while (text != null) {
stngFile.add(text);
text = bfredr.readLine();
}
bfredr.close();
String[] array = stngFile.toArray(new String[0]);
Arrays.toString(array);
for (String eachstring : array) {
System.out.println(eachstring);
}
}
}
}

JFileChooser.SetCurrentDirectory not working

I have a JFileChooser and I want to set the directory it opens using some information stored in a .txt file (I'm using a .txt file to persist the desired location between sessions). I can get the file, read the data and set it to a string, but when I try to use that string to set the directory I want to open it doesn't work. My code is roughly something like this:
//buffer contains a byte[] for "/Users/user/Documents/Work/folderToOpen"
desiredPath = new String(buffer);
jFileChooser1.setCurrentDirectory(new java.io.File(desiredPath));
After stepping through this, however, the current directory is set to /Users/user.
If anyone has any ideas about what I'm doing wrong or a better way to accomplish this I'd love to hear it.
Thank you
private static String LAST_FOLDER_USED = null;
//Get the desired file path for user preferences
String pluginRoot = System.getProperty("user.dir") + File.separator.toString();
//Create a file using the desired file Path
File userPreferences = new File(pluginRoot + File.separator + "UserPreferences.txt");
//Get a file called UserPreferences.txt from target/classes to create an input stream
String fileName = "UserPreferences.txt";
InputStream readInFile = getClass().getResourceAsStream(fileName);{
//Convert input stream to read from the desired file in the plug-in root ("filePath" Created Above)
try{
readInFile = new FileInputStream(userPreferences);
}
catch (IOException e){
e.printStackTrace();
}}
//Read the readInFile into a byte[]
String desiredPathToOpenImage;
byte[] buffer = new byte[1000];
int i = 0;{
try {
while((i = readInFile.read(buffer)) !=-1){
System.out.println(new String(buffer));
i++;
}}
catch (IOException e) {
e.printStackTrace();
};
//Convert byte[] to string (This should be the path to the desired folder when selecting an image)
desiredPathToOpenImage = new String(buffer);
}
//Create a New File using the desired path
File desiredPath = new File(desiredPathToOpenImage + File.separator + "prefs.txt");
public SelectImage(Viewer parent, boolean modal) {
super(parent, modal);
initComponents();
int returnVal = jFileChooser1.showOpenDialog(parent);
// Sets up arrays for storing file information to be passed back to the viewer class.
String[] filePath = new String[jFileChooser1.getSelectedFiles().length];
String[] fileName = new String[jFileChooser1.getSelectedFiles().length];
String[] fileDir = new String[jFileChooser1.getSelectedFiles().length];
if (returnVal == JFileChooser.APPROVE_OPTION) {
// Cycles through the selected files and stores each piece accordingly
for (int i = 0; i < jFileChooser1.getSelectedFiles().length; i++) {
File file = jFileChooser1.getSelectedFiles()[i];
filePath[i] = file.getPath();
fileName[i] = file.getName();
fileDir[i] = file.getParent();
}
}
parent.setFilePath(filePath, fileName, fileDir);
}
private void initComponents() {
jFileChooser1 = new javax.swing.JFileChooser();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jFileChooser1.setMultiSelectionEnabled(true);
//Checks folder_Path to see if a value is present. If value is present sets jFileChooser Directory to that value
if(desiredPathToOpenImage.contains(File.separator)){
//Create a File using the desired path for selecting images
//****Currently doesn't set the Directory correctly****//
jFileChooser1.setCurrentDirectory(desiredPath);
}
//If no value is present in LAST_FOLDER_USED sets jFileChooser Directory to desktop
else{
jFileChooser1.setCurrentDirectory(new java.io.File("/Users/benwoodruff/Desktop"));
}
jFileChooser1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jFileChooser1ActionPerformed(evt);
//After file is selected sets value of LAST_FOLDER_USED to the absolute path of that file
LAST_FOLDER_USED = jFileChooser1.getCurrentDirectory().toString() + File.separator + "UserPreferences.txt";
try {
FileWriter fileWriter = new FileWriter(userPreferences);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(jFileChooser1.getCurrentDirectory().toString());
OutputStream outPut = new FileOutputStream(pluginRoot + File.separator + "UserPreferences.txt");
outPut.write(LAST_FOLDER_USED.getBytes());
outPut.close();
bufferedWriter.close();
} catch (IOException e) {
System.out.println("Error Writing to File" + desiredPathToOpenImage);
e.printStackTrace();
}
}
});
I think the directory passed as argument does not exist or is not accessible to the user you are logged in with judging from the javadoc of setCurrentDirectory():
If the file passed in as currentDirectory is not a directory, the parent of the file will be used as the currentDirectory. If the parent is not traversable, then it will walk up the parent tree until it finds a traversable directory, or hits the root of the file system.
Make sure all folders in the given path exist and are accessible to the logged user (on linux the 'executable' bit controls the accessibility of a directory). So if you see something like
-d x Documents
after executing
ls -l *
in a shell then the Documents directory is accessible.
Found a better way to accomplish my goal using Preferences instead of trying to create and access files to store the location.
Preferences prefs = Preferences.userNodeForPackage(this.getClass());
static String LAST_FOLDER_USED = "LAST_FOLDER_USED";
String folder_Location;
and then inside initComponents()
if(LAST_FOLDER_USED != null){
jFileChooser1.setCurrentDirectory(new File(prefs.get(LAST_FOLDER_USED, LAST_FOLDER_USED)));
}
else{
jFileChooser1.setCurrentDirectory(new java.io.File("/Users/benwoodruff/Desktop"));
}
jFileChooser1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jFileChooser1ActionPerformed(evt);
folder_Location = jFileChooser1.getCurrentDirectory().toString();
prefs.put(LAST_FOLDER_USED, folder_Location);
//System.out.println(prefs.get(LAST_FOLDER_USED, folder_Location));
}
});

Copying Multiple files using SWT filedialog

I'm working a transfer file program and my program is working but I'm having a problem because when I select multiple files and put it on a textbox the source directory can't read what is on the textbox
this is my code
Opening file/files
btnSearchFile.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
FileDialog fd = new FileDialog(shell, SWT.MULTI);
Collection files = new ArrayList();
String firstFile = fd.open();
if (firstFile != null) {
String[] selectedFiles = fd.getFileNames();
File file = new File(firstFile);
for (int ii = 0; ii < selectedFiles.length; ii++ )
{
if (file.isFile())
{
displayFiles(new String[] { file.toString()});
}
else
displayFiles(file.list());
}
}
}
});
Displaying Files on textbox
public void displayFiles(String[] files) {
for (int i = 0; files != null && i < files.length; i++) {
txtSource.append(files[i]);
txtSource.setEditable(false);
}
}
Copy Files
public static void copyFile(File src, File dest) throws IOException
{
InputStream oInStream = new FileInputStream(src);
OutputStream oOutStream = new FileOutputStream(dest);
// Transfer bytes from in to out
byte[] oBytes = new byte[1024];
int nLength;
BufferedInputStream oBuffInputStream = new BufferedInputStream( oInStream );
while ((nLength = oBuffInputStream.read(oBytes)) > 0)
{
oOutStream.write(oBytes, 0, nLength);
}
oInStream.close();
oOutStream.close();
}
PS: One file is okay but if multiple files are selected and put on the textbox the source directory can't be found
In order to be completely helpful, we could really use some more detail (specific exceptions, a complete MCVE, which SWT widgets are used, etc.).
That said, I think you've provided enough to see that there are some issues with your code:
For starters, when you have multiple files selected, you're displaying the same file name (the name of the first one) over and over. Perhaps this is intentional, but worth mentioning:
String[] selectedFiles = fd.getFileNames();
File file = new File(firstFile);
for (int ii = 0; ii < selectedFiles.length; ii++ )
{
// You've used a FileDialog, so this should always be true
if (file.isFile())
{
// Will always be the first file
displayFiles(new String[] { file.toString()});
}
else
displayFiles(file.list());
}
Based on the context, I'm assuming txtSource is a Text widget. With that in mind, if we look at your displayFiles() method, you have the following:
txtSource.append(files[i]);
When you call displayFiles() repeatedly, you will be tacking on a file name after all the others, effectively building one long String which is the combination of all file names. When you go to copy the files listed, splitting that String back into valid file paths will be tricky.
My guess is that when you say:
"the source directory can't be found"
...you're just grabbing the content of txtSource. Something like this:
new File(txtSource.getText());
"...One file is okay..."
That will certainly work if there's only one file name in the Text object, but if there are multiple names it will result in a non-existent File.
For example, if you've selected two files:
C:\Users\me\FileA
C:\Users\me\FileB
Your txtSource would display C:\Users\me\FileAC:\Users\me\FileB. And the path C:\Users\me\FileAC:\Users\me\FileB most likely does not exist.
In that case, new File(txtSource.getText()).exists() would return false, and using that File in the constructor for FileInputStream (inside copyFile()) would result in a FileNotFoundException.
In short, just make sure that when you make your call to copyFile() and create the source File object that you're giving the path that you think you are, and not the concatenation of all files selected.

Having a variable from another class as the file name (GUI)

One class of my GUI has a variable for the file name. I want to pass this to another class so that I can process a file without having to hard code the file's name every time. The program compiles fine but I can't seem to run it correctly.
public void run() {
WordsCounter2 fileName = new WordsCounter2();
essayName = fileName.getFileList();
File f = new File(essayName);
//other code
WordsCounter2 is the class that houses the variable fileName, I'm calling it from this class and assigning it as the file's name, but this doesn't work. Could someone help?
if (rVal == JFileChooser.APPROVE_OPTION) {
File[] selectedFile = fileChooser.getSelectedFiles();
fileList = "nothing";
if (selectedFile.length > 0)
fileList = selectedFile[0].getName();
for (int i = 1; i < selectedFile.length; i++) {
fileList += ", " + selectedFile[i].getName();
}
statusBar.setText("You chose " + fileList);
}
else {
statusBar.setText("You didn't choose a file.");
}
fileList isn't empty because I have a label on the GUI that lists whatever file I chose.
Here's my new edit: now the exception occurs at the last line with the scanner and throws a NPE. Can you help?
public void run() {
WordsCounter2 pathNamesList = new WordsCounter2();
essayName = pathNamesList.getPathNamesList();
essayTitle = new String[essayName.size()];
essayTitle = essayName.toArray(essayTitle);
for (int i = 0; i < essayTitle.length; i++) {
f = new File(essayTitle[i]);
}
try {
Scanner scanner = new Scanner(f);
Your code is failing because File will not accept comma separated file names, in fact, it needs a single file path to create the file in the mentioned path. See here: https://docs.oracle.com/javase/7/docs/api/java/io/File.html
You'll have to get complete paths in an array and put the file creation statement as follows:
File f;
for (int i=0; i<fileList.length; i++)
f = new File(fileList[i]);
where fileList is a String array holding the list of pathnames.
In case you're trying to write some content to these files as well, this should be helpful: Trying to Write Multiple Files at Once - Java

Search a text file for List of names in JAVA

I have the following:
Folder that contains many files (about 300000), named "AllFilesFolder"
list of names, named "namesList"
An empty folder, named "filteredFolder"
I want to filter the folder "AllFilesFolder", by moving any file that contins any of the names in the list to the empty folder "filteredFolder".
I have approche this problem by the following code:
public static void doIt(List<String>namesList, String AllFilesFolder, String filteredFolder) throws FileNotFoundException {
// here we put all the files in the original folder in List variable name "filesList"
File[] filesList = new File(AllFilesFolder).listFiles();
// went throught the files one by one
for (File f : filesList) {
try {
FileReader fr = new FileReader(f);
BufferedReader reader = new BufferedReader(fr);
String line = "";
//this varibale used to test withir the files contins names or not
//we set it to false.
boolean goodDoc = false;
//go through the file line by line to chick the names (I wounder if there are a simbler whay)
while ((line = reader.readLine()) != null) {
for(String name:namesList){
if ( line.contains(name)) {
goodDoc = true;
}
}
}
reader.close();
// if this file contains the name we put this file into the other folder "filteredFolder"
if (goodDoc) {
InputStream inputStream = new FileInputStream(f);
OutputStream out = new FileOutputStream(new File(filteredFolder + f.getName()));
int read = 0;
byte[] bytes = new byte[4096];
while ((read = inputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
inputStream.close();
out.flush();
out.close();
}
} catch (Exception e) {
System.err.println(e);
}
}
}
By doing this I have two problems that I need your advice to solve:
I am reading each file twice, one time to search and the other to put it into the other folder.
When searching namesList I have for loop to takes the names one by one, Is there a way to search the list one time (without loop).
Many thanks in advance
I am reading each file twice, one time to search and the other to put it into the other folder.
Using NIO improves the copy performance. Here is the code example. If you can use Java 7 then you can use Files.copy()
When searching namesList I have for loop to takes the names one by one, Is there a way to search the list one time (without loop).
Use HashSet to store the names and use contains() method. It is a O(1) operation. Or another suggestion is to use Scanner.findWithinHorizon(pattern, horizon)

Categories