使用 fileChooser 将 txt 文件复制到数组(逐字)
Copy txt files to array (word by word) with using fileChooser
伙计们,我在 Java.I 同时使用 fileChooser 和使用 File reader 时遇到问题需要帮助。
使用 fileChooser 将 txt 文件逐字复制到数组(每个字将保持不同的数组索引号)。
在 actionPerformed 方法中写入:
final JFileChooser fc = new JFileChooser("E://");
int returnVal = fc.showOpenDialog(this);
System.out.println(returnVal);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
String p = file.getPath();
try(BufferedReader bufRead = new BufferedReader(new FileReader(p)))
{
StringBuilder sb = new StringBuilder();
String s = "";
while((s=bufRead.readLine())!=null)
{
sb.append(s+" ");
}
String[] words= sb.toString().split(" ");
for(String a:words)
{
System.out.println(a);// printing out each word
}
}
catch(FileNotFoundException e)
{
System.out.println("File not found : "+e.getMessage());
}
catch(IOException ex)
{
System.out.println("Exception : "+ex.getMessage());
}
}
else
{
System.out.println("Open command cancelled by user.");
}
我在这里打印出每个单词。您可以对存储在数组中的单词执行任何操作。希望对您有所帮助。
伙计们,我在 Java.I 同时使用 fileChooser 和使用 File reader 时遇到问题需要帮助。 使用 fileChooser 将 txt 文件逐字复制到数组(每个字将保持不同的数组索引号)。
在 actionPerformed 方法中写入:
final JFileChooser fc = new JFileChooser("E://");
int returnVal = fc.showOpenDialog(this);
System.out.println(returnVal);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
String p = file.getPath();
try(BufferedReader bufRead = new BufferedReader(new FileReader(p)))
{
StringBuilder sb = new StringBuilder();
String s = "";
while((s=bufRead.readLine())!=null)
{
sb.append(s+" ");
}
String[] words= sb.toString().split(" ");
for(String a:words)
{
System.out.println(a);// printing out each word
}
}
catch(FileNotFoundException e)
{
System.out.println("File not found : "+e.getMessage());
}
catch(IOException ex)
{
System.out.println("Exception : "+ex.getMessage());
}
}
else
{
System.out.println("Open command cancelled by user.");
}
我在这里打印出每个单词。您可以对存储在数组中的单词执行任何操作。希望对您有所帮助。