gpt4 book ai didi

java - 使用 JFileChooser 将某些文本从 JTextArea 保存到文件

转载 作者:太空宇宙 更新时间:2023-11-04 15:15:00 25 4
gpt4 key购买 nike

我的 JTextArea 中有此文本:

Getting all .mp3 files in C:\Users\Admin\Music including those in subdirectories

C:\Users\Admin\Music\Sample Music\Kalimba.mp3
C:\Users\Admin\Music\Sample Music\Maid with the Flaxen Hair.mp3
C:\Users\Admin\Music\Sample Music\Sleep Away.mp3

Finished Searching...

我只想保存这部分:

C:\Users\Admin\Music\Sample Music\Kalimba.mp3
C:\Users\Admin\Music\Sample Music\Maid with the Flaxen Hair.mp3
C:\Users\Admin\Music\Sample Music\Sleep Away.mp3

不幸的是我不能使用下面的代码:

JFileChooser saveFile = new JFileChooser("./");  
int returnVal = saveFile.showSaveDialog(this);
File file = saveFile.getSelectedFile();
BufferedWriter writer = null;
if (returnVal == JFileChooser.APPROVE_OPTION)
{
try {
writer = new BufferedWriter( new FileWriter( file.getAbsolutePath()+".txt")); // txt for now but needs to be m3u
searchMP3Results.write(writer); // using JTextArea built-in writer
writer.close( );
JOptionPane.showMessageDialog(this, "Search results have been saved!",
"Success", JOptionPane.INFORMATION_MESSAGE);
}
catch (IOException e) {
JOptionPane.showMessageDialog(this, "An error has occured",
"Failed", JOptionPane.INFORMATION_MESSAGE);
}
}

使用上面的代码,它保存了 JTextArea 中的所有内容。你能帮我吗?

附注如果可能的话,我想将其保存为 M3U 播放列表。

最佳答案

我假设 searchMP3Results 是包含文本的 JTextArea。在这种情况下,您可以使用 searchMP3Results.getText()String 形式获取文本,并通过查找文件路径的正则表达式运行结果。 Windows 路径的正则表达式示例位于此问题 java regular expression to match file path 上。 。不幸的是,这将您的应用程序与 Windows 联系在一起,但如果这是可以接受的,那么您就可以开始了,否则您应该使用系统属性检测操作系统并选择正确的正则表达式。

就 m3u 而言,您应该只能导出目录路径(每行一个)。扩展 m3u 文件(使用 header #EXTM3U)需要其他信息,但您应该能够使用简单版本。

更新:添加代码更新 2:将正则表达式更改为路径正则表达式(副文件)的修改版本,现在针对每一行运行它,而不是执行多行评估

String text = searchMP3Results.getText();
StringBuilder output = new StringBuilder();
for ( String s : text.split("\n") ) {
if ( java.util.regex.Pattern.matches("^([a-zA-Z]:)?(\\\\[\\s\\.a-zA-Z0-9_-]+)+\\\\?$", s) ) {
output.append(s).append("\n");
}
}

此代码将输入拆分为行数组(您可能需要使用 \r\n 而不仅仅是 \n),然后使用正则表达式来检查如果该行是路径/文件名组合。不执行进一步的检查,并且路径/文件名被假定为有效,因为它可能来自外部应用程序。我的意思是正则表达式不会检查路径/文件名中的无效字符,也不会检查文件是否存在,尽管添加起来很简单。

关于java - 使用 JFileChooser 将某些文本从 JTextArea 保存到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20942757/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com