Codename One开发:如何使用FileChooser返回的CSV文件路径?
Codename One FileChooser返回file:// URL的CSV读取解决方案
代码错误修正
你这段代码存在类型不匹配问题:
FileSystemStorage fs = FileSystemStorage.getInstance().exists(file);
exists()返回布尔值,不能赋值给FileSystemStorage对象,正确写法:
FileSystemStorage fs = FileSystemStorage.getInstance(); boolean fileExists = fs.exists(file);
处理file://格式路径
桌面端FileChooser返回的file://协议URL无法直接被FileSystemStorage识别,需要转换为本地文件路径:
方案1:直接截取路径
针对桌面端的file:///xxx格式,去掉前缀即可:
if (file.startsWith("file://")) { // 移除开头的"file:///" file = file.substring(7); } InputStream is = fs.openInputStream(file); // 传入CSVParser处理 CSVParser parser = new CSVParser(is, ',');
方案2:用Codename One工具类适配多平台
使用Util类的getLocalFilePath方法,适配不同平台的路径格式:
import com.codename1.io.Util; String localPath = Util.getLocalFilePath(file); if (localPath != null) { InputStream is = FileSystemStorage.getInstance().openInputStream(localPath); // 执行CSV解析逻辑 }
Maven依赖规范修复
手动创建pom文件夹的方式可临时解决依赖问题,但更规范的做法是在pom.xml中正确引入依赖:
<dependency> <groupId>com.codenameone</groupId> <artifactId>filechooser-lib</artifactId> <version>2.0.0</version> <type>pom</type> </dependency>
执行mvn clean install重新拉取依赖,避免手动修改本地仓库引发后续问题。
临时文件处理提示
桌面端FileChooser生成的临时文件会在应用退出后被系统清理,若需长期使用,建议复制到应用私有存储目录:
String appStorage = FileSystemStorage.getInstance().getAppHomePath(); String savedFile = appStorage + "selected_data.csv"; Util.copy(fs.openInputStream(localPath), fs.openOutputStream(savedFile)); // 后续操作savedFile即可
内容的提问来源于stack exchange,提问作者curtjacobs1
相关产品推荐
相关产品推荐

