java - 无法使用 OpenCSV 写入文件
问题描述
我正在尝试将文件写入目录。由于 RxBleClient 将搜索蓝牙低能耗客户端的结果返回到 ArrayList,我使用了 RxJava。然后我需要创建并打开一个具有自定义名称的文件以将结果保存到其中。我在 Android Doc 上搜索以检查我是否已授予所有权限,编写了一些代码以确保这一点 - 全部授予。我不知道如何解决这个问题。下面是代码、堆栈跟踪和清单文件。
private void scanBleDevicesDelay(int howManyRows, String filename) {
scanDisposable = rxBleClient.scanBleDevices(
new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) // change if needed
.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES) // change if needed
.build(),
new ScanFilter.Builder()
.build())
.doFinally(() -> {
dispose();
toggleScanBleButton.setEnabled(true);
dumpToFileButton.setEnabled(true);
})
.subscribe(
scanResult -> {
// I am not proud of this :-(
// Process scan result here.
recycleViewBLEAdapter.addScanResult(scanResult);
scanResultsCSV.add(scanResult);
if (scanResultsCSV.size() == howManyRows) {
// CSV file writer
try {
if (ContextCompat.checkSelfPermission(
getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_GRANTED) {
// You can use the API that requires the permission.
// performAction(...);
File pathfile = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath()
+ File.separator
+ "csvData");
if (!pathfile.isDirectory()) {
// ~~~~~~~~~~~~~~~~~~IS NOT CREATING A DIRECTORY~~~~~~~~~~~~~~~~~~
pathfile.mkdir();
}
File file = new File(pathfile,
File.separator + filename + ".csv");
if (!file.exists()) {
// ~~~~~~~~~~~~~~~~~~IS NOT CREATING A FILE~~~~~~~~~~~~~~~~~~
// ~~~~~~~~~~~~~~~~~~HERE THROWS IOException ~~~~~~~~~~~~~~~~~~
file.createNewFile();
// Files.createFile(file.toPath());
Log.i("File created: ", file.getName());
}
CSVWriter writer = new CSVWriter(new FileWriter(file));
// CSVWriter writer = new CSVWriter(new FileWriter(pathfile + File.separator + filename + ".csv"));
scanResultsCSV.forEach(scan -> {
String[] entries = String.format("%s,%s,%s", scan.getTimestampNanos(), scan.getBleDevice(), scan.getRssi()).split(",");
Log.i("Entries", Arrays.toString(entries));
writer.writeNext(entries);
});
writer.close();
Toast.makeText(this, "Zapisano do pliku", Toast.LENGTH_SHORT).show();
} else if (shouldShowRequestPermissionRationale("Failed")) {
// In an educational UI, explain to the user why your app requires this
// permission for a specific feature to behave as expected. In this UI,
// include a "cancel" or "no thanks" button that allows the user to
// continue using your app without granting the permission.
// showInContextUI(...);
Toast.makeText(this, "Nie przyznano dostępu", Toast.LENGTH_SHORT).show();
} else {
// request a permission
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE}, 3);
}
} catch (IOException ioException) {
ioException.printStackTrace();
Toast.makeText(this, "Plik istnieje!", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "Nieoczekiwany blad", Toast.LENGTH_SHORT).show();
} finally {
// Toast.makeText(this, "Zakonczono procedure", Toast.LENGTH_SHORT).show();
scanDisposable.dispose();
}
}
},
throwable -> {
// Handle an error here.
Log.e("BLE search error", Arrays.toString(throwable.getStackTrace()));
Toast.makeText(this, "Nieoczekiwany blad", Toast.LENGTH_SHORT).show();
}
);
}
并在Manifest file
:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
堆栈跟踪:
W/System.err: java.io.IOException: No such file or directory
at java.io.UnixFileSystem.createFileExclusively0(Native Method)
at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:317)
W/System.err: at java.io.File.createNewFile(File.java:1008)
at com.example.ble_rssi_plotter.MainActivity.lambda$scanBleDevicesDelay$4$MainActivity(MainActivity.java:291)
W/System.err: at com.example.ble_rssi_plotter.-$$Lambda$MainActivity$k9iEru6y1TGq9ZgTipfCtV0GZ18.accept(Unknown Source:8)
at io.reactivex.internal.observers.LambdaObserver.onNext(LambdaObserver.java:63)
W/System.err: at io.reactivex.internal.operators.observable.ObservableDoFinally$DoFinallyObserver.onNext(ObservableDoFinally.java:80)
at io.reactivex.internal.operators.observable.ObservableFlatMap$MergeObserver.tryEmit(ObservableFlatMap.java:265)
at io.reactivex.internal.operators.observable.ObservableFlatMap$InnerObserver.onNext(ObservableFlatMap.java:562)
at io.reactivex.internal.operators.observable.ObservableDoOnEach$DoOnEachObserver.onNext(ObservableDoOnEach.java:101)
W/System.err: at io.reactivex.internal.operators.observable.ObservableMap$MapObserver.onNext(ObservableMap.java:62)
at io.reactivex.internal.operators.observable.ObservableUnsubscribeOn$UnsubscribeObserver.onNext(ObservableUnsubscribeOn.java:60)
at io.reactivex.internal.operators.observable.ObservableCreate$CreateEmitter.onNext(ObservableCreate.java:66)
W/System.err: at com.polidea.rxandroidble2.internal.serialization.FIFORunnableEntry$1$1.onNext(FIFORunnableEntry.java:68)
at io.reactivex.internal.operators.observable.ObservableUnsubscribeOn$UnsubscribeObserver.onNext(ObservableUnsubscribeOn.java:60)
at io.reactivex.internal.operators.observable.ObservableCreate$CreateEmitter.onNext(ObservableCreate.java:66)
W/System.err: at com.polidea.rxandroidble2.internal.operations.ScanOperationApi21$1.onScanResult(ScanOperationApi21.java:77)
at android.bluetooth.le.BluetoothLeScanner$BleScanCallbackWrapper$1.run(BluetoothLeScanner.java:492)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:7656)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
解决方案
推荐阅读
- linux-containers - Podman 如果有很多容器,如何删除所有退出的容器
- c# - 为什么我不能使用此 ForEach 循环将整数分配给数组(抛出“未设置对象引用”异常)
- flutter - 读取继承自 stateNotifier 的类中的状态
- python - 合并两个排序的python列表
- javascript - 如果使用Angular为空日期选择器,如何禁用按钮
- c++ - 如何将函数调用与回调同步?
- sql - 使用SQL将数据从阿拉伯语翻译成英语,数据库是oracle
- google-api - 无法在 Google Calendar API 中获取我拥有的列表
- spring-boot - 使用 springboot_springdata_JPA 生成动态查询时面临问题。未生成所需的查询
- python - 堆叠列