Java 如何使用Swings应用程序上载多个文件?
我试图在swings应用程序中上载多个文件。我声明了一个数组来保存所选文件的值,但当我单击“上载”按钮时,只上载了一个文件。如何将所有选定的文件上载到数据库中 打开和上载文件的代码是Java 如何使用Swings应用程序上载多个文件?,java,swing,Java,Swing,我试图在swings应用程序中上载多个文件。我声明了一个数组来保存所选文件的值,但当我单击“上载”按钮时,只上载了一个文件。如何将所有选定的文件上载到数据库中 打开和上载文件的代码是 public void openFile() { JFileChooser jfc = new JFileChooser(); jfc.setMultiSelectionEnabled(true);// added line int result = jfc.showOpe
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);
}
}
public void openFile()
{
JFileChooser jfc=新的JFileChooser();
jfc.setMultiSelectionEnabled(true);//添加了行
int result=jfc.showOpenDialog(此);
if(result==JFileChooser.CANCEL_选项)返回;
试一试{
ArrayList FileData=新的ArrayList();
File[]File=jfc.getSelectedFiles();
字符串s=“”;int c=0;
对于(int i=0;i
由于要读取多个文件的内容,只需在循环中执行此操作,然后逐个执行。如果在内存中加载所有文件,则可能会遇到问题。您尚未明确定义“上载多个文件”的实际含义。我假设您希望将多个文本文件的内容一个接一个地加载到一个JEditorPane
中。如果是这样,Romain的回答将向您展示一个加载单个文件的示例。
不过,您的代码实际上是在文件
对象数组中循环,并将它们的路径(即toString
在文件
中返回的路径)设置为编辑器窗格中的文本。每一个对象都覆盖最后一个对象,这就是为什么您最终会得到一个文件路径。
我还建议您在弹出JFileChooser
时,将用户可以选择的文件限制为特定的文件类型(例如txt、html).请给我们看一下上传/保存数据的代码。把我的水晶球留在家里……似乎问题出在按钮后面的代码中,而不是按钮本身。你应该看看那里。Swing不是J2EE的一部分。在以后的Swing问题中,只需标记[Swing]
,而不是[J2EE]
。您的代码片段不正确:您返回了void方法上的数组列表,没有告诉我们您在哪里定义了jep,等等。
// 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;
/**
* 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;
}