feat: 完善错误处理打印
This commit is contained in:
		
							parent
							
								
									b04ab92f9b
								
							
						
					
					
						commit
						63bc3f42d6
					
				| @ -1,5 +1,6 @@ | ||||
| export const DbTag = '[DBTag]'; | ||||
| 
 | ||||
| // 串口 tag | ||||
| export const SerialPortTag = '[SerialPortTag]'; | ||||
| 
 | ||||
| // usb tag | ||||
| @ -18,4 +19,7 @@ export const FileTag = '[FileTag]'; | ||||
| export const TCPTag = '[TcpClient]'; | ||||
| 
 | ||||
| //udp tag | ||||
| export const UDPTag = '[UdpClient]'; | ||||
| export const UDPTag = '[UdpClient]'; | ||||
| 
 | ||||
| //fileHelp tag | ||||
| export const FileHelpTag = '[FileHelp]'; | ||||
| @ -3,7 +3,6 @@ import hilog from '@ohos.hilog'; | ||||
| import window from '@ohos.window'; | ||||
| import { GlobalConfig } from '../config/global'; | ||||
| import { initTable } from '../common/service/initable'; | ||||
| import { centerUDPClient, lightUDPClient, objUDPClient } from '../utils/UdpUtils'; | ||||
| import Want from '@ohos.app.ability.Want'; | ||||
| import AbilityConstant from '@ohos.app.ability.AbilityConstant'; | ||||
| import { BaseInfoType, CarInfoType, ExaminerInfoType } from '../model'; | ||||
| @ -33,10 +32,6 @@ export default class EntryAbility extends UIAbility { | ||||
|   } | ||||
| 
 | ||||
|   async onWindowStageCreate(windowStage: window.WindowStage) { | ||||
|     // 初始化示例,只需要调用一次 | ||||
|     await objUDPClient.init(this.context) | ||||
|     await lightUDPClient.init(this.context) | ||||
|     await centerUDPClient.init(this.context) | ||||
|     // this.context | ||||
|     // Main window is created, set main page for this ability | ||||
|     hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); | ||||
|  | ||||
| @ -1,4 +1,4 @@ | ||||
| import dayTs from "./Date"; | ||||
| import dayTs from './Date'; | ||||
| 
 | ||||
| enum timeType { | ||||
|   fulltime = 1 | ||||
| @ -44,15 +44,6 @@ export function StringToBytes(str: string): Uint8Array { | ||||
|   } | ||||
|   return bytes; | ||||
| } | ||||
| // import { | ||||
| //   Array2Byte, | ||||
| //   convertGpsCoord2, | ||||
| //   deepClone, | ||||
| //   fillZero, | ||||
| //   getCurrentTime, | ||||
| //   string2Bytes, | ||||
| //   stringToASC | ||||
| // } from '../../common/utils/tools'; | ||||
| 
 | ||||
| /** | ||||
|  * 字符串转ASCII码 | ||||
|  | ||||
| @ -1,7 +1,7 @@ | ||||
| import relationalStore from '@ohos.data.relationalStore' | ||||
| import common from '@ohos.app.ability.common' | ||||
| import { BusinessError } from '@ohos.base' | ||||
| import { DbTag } from "../config" | ||||
| import { DbTag } from '../config' | ||||
| 
 | ||||
| export interface ColumnInfo { | ||||
|   name: string, | ||||
| @ -27,11 +27,11 @@ class DbUtils { | ||||
|       relationalStore.getRdbStore(context, config) | ||||
|         .then(rdbStore => { | ||||
|           this.rdbStore = rdbStore | ||||
|           console.info("db rdbStore init success") | ||||
|           console.log(DbTag, "db rdbStore init success") | ||||
|           resolve() | ||||
|         }) | ||||
|         .catch((err: BusinessError) => { | ||||
|           console.error(`db rdbStore init fail reason:${err}`); | ||||
|           console.error(DbTag, `db rdbStore init fail reason:${err}`); | ||||
|           reject(err) | ||||
|         }) | ||||
| 
 | ||||
| @ -44,11 +44,11 @@ class DbUtils { | ||||
|       if (this.rdbStore) { | ||||
|         this.rdbStore?.executeSql(createSql) | ||||
|           .then(() => { | ||||
|             console.info("sql createTable success") | ||||
|             console.log(DbTag, "sql createTable success") | ||||
|             resolve() | ||||
|           }) | ||||
|           .catch((err: BusinessError) => { | ||||
|             console.error(`sql createTable fail err:${JSON.stringify(err)}`); | ||||
|             console.error(DbTag, `sql createTable fail err:${JSON.stringify(err)}`); | ||||
|             reject(err) | ||||
|           }) | ||||
|       } else { | ||||
| @ -92,10 +92,10 @@ class DbUtils { | ||||
|       if (this.rdbStore) { | ||||
|         this.rdbStore?.insert(tableName, obj, (err, res) => { | ||||
|           if (err) { | ||||
|             console.error(`sql insertData fail err:${JSON.stringify(err)}`); | ||||
|             console.error(DbTag, `sql insertData fail err:${JSON.stringify(err)}`); | ||||
|             reject(err) | ||||
|           } else { | ||||
|             console.info(`sql insertData success res:${res}`); | ||||
|             console.log(DbTag, `sql insertData success res:${res}`); | ||||
|             resolve(res) | ||||
|           } | ||||
|         }) | ||||
| @ -113,7 +113,7 @@ class DbUtils { | ||||
|         console.log(DbTag, "删除表成功!表名:", tableName) | ||||
|         resolve(true) | ||||
|       }).catch((err: BusinessError) => { | ||||
|         console.log(DbTag, "删除表失败!表名:", tableName, "错误信息:", JSON.stringify(err)) | ||||
|         console.error(DbTag, "删除表失败!表名:", tableName, "错误信息:", JSON.stringify(err)) | ||||
|         reject(false) | ||||
|       }) | ||||
|     }) | ||||
| @ -132,7 +132,7 @@ class DbUtils { | ||||
|     return new Promise((resolve, reject) => { | ||||
|       if (this.rdbStore) { | ||||
|         this.rdbStore.querySql(sql, []).then((res: relationalStore.ResultSet) => { | ||||
|           console.log("sql query", JSON.stringify(res)) | ||||
|           console.log(DbTag, "sql query", JSON.stringify(res)) | ||||
|           if (res.rowCount <= 0) { | ||||
|             resolve(null) | ||||
|           } else { | ||||
| @ -140,7 +140,7 @@ class DbUtils { | ||||
|             resolve(res.getLong(0) as T) | ||||
|           } | ||||
|         }).catch((err: BusinessError) => { | ||||
|           console.error(`sql queryCount fail err:${JSON.stringify(err)}`); | ||||
|           console.error(DbTag, `sql queryCount fail err:${JSON.stringify(err)}`); | ||||
|           reject(err) | ||||
|         }) | ||||
|       } else { | ||||
| @ -155,10 +155,10 @@ class DbUtils { | ||||
|       if (this.rdbStore) { | ||||
|         this.rdbStore?.query(predicates, columns.map(info => info.columnName), (err, result) => { | ||||
|           if (err) { | ||||
|             console.error(`sql queryForList fail err:${JSON.stringify(err)}`); | ||||
|             console.error(DbTag, `sql queryForList fail err:${JSON.stringify(err)}`); | ||||
|             reject(err) | ||||
|           } else { | ||||
|             console.info(`sql queryForList success rows: ${result.rowCount.toString()}`) | ||||
|             console.log(DbTag, `sql queryForList success rows: ${result.rowCount.toString()}`) | ||||
|             resolve(this.parseResultSet(result, columns)) | ||||
|           } | ||||
|         }) | ||||
| @ -174,7 +174,7 @@ class DbUtils { | ||||
|       if (this.rdbStore) { | ||||
|         this.rdbStore?.querySql(sql, [], (err, result) => { | ||||
|           if (err) { | ||||
|             console.error(`sql queryForListBySql fail err:${JSON.stringify(err)}`); | ||||
|             console.error(DbTag, `sql queryForListBySql fail err:${JSON.stringify(err)}`); | ||||
|             reject(err) | ||||
|           } else { | ||||
|             resolve(this.parseResultSet(result, columns)) | ||||
| @ -224,11 +224,11 @@ class DbUtils { | ||||
|       if (this.rdbStore) { | ||||
|         this.rdbStore?.delete(predicates) | ||||
|           .then(rows => { | ||||
|             console.info(`DbUtil delete success rows: ${rows.toString()}`) | ||||
|             console.log(DbTag, `DbUtil delete success rows: ${rows.toString()}`) | ||||
|             resolve(rows) | ||||
|           }) | ||||
|           .catch((err: BusinessError) => { | ||||
|             console.error(`DbUtil delete fail err:${JSON.stringify(err)}`); | ||||
|             console.error(DbTag, `DbUtil delete fail err:${JSON.stringify(err)}`); | ||||
|             reject(err) | ||||
|           }) | ||||
|       } else { | ||||
|  | ||||
| @ -2,6 +2,7 @@ import photoAccessHelper from '@ohos.file.photoAccessHelper'; | ||||
| import dataSharePredicates from '@ohos.data.dataSharePredicates'; | ||||
| import common from '@ohos.app.ability.common'; | ||||
| import { BusinessError } from '@ohos.base'; | ||||
| import { FileHelpTag } from '../config'; | ||||
| 
 | ||||
| export class FileHelper { | ||||
|   FILE_ASSET_FETCH_COLUMNS = [ | ||||
| @ -30,7 +31,7 @@ export class FileHelper { | ||||
|   } | ||||
| 
 | ||||
|   public async queryPhotoByDisplayName(displayName: string) { | ||||
|     console.log('baoyihu queryPhotoByDisplayName begin DISPLAY_NAME:' + displayName); | ||||
|     console.log(FileHelpTag, ' queryPhotoByDisplayName begin DISPLAY_NAME:' + displayName); | ||||
|     try { | ||||
|       let predicates = new dataSharePredicates.DataSharePredicates(); | ||||
|       predicates.equalTo(photoAccessHelper.PhotoKeys.DISPLAY_NAME, displayName) | ||||
| @ -41,15 +42,15 @@ export class FileHelper { | ||||
|       let assetsResult = await this.userFileMgr.getAssets(fetchOptions); | ||||
| 
 | ||||
|       let retCount = assetsResult.getCount(); | ||||
|       console.log('baoyihu queryPhotoByDisplayName count: ' + retCount); | ||||
|       console.log(FileHelpTag, ' queryPhotoByDisplayName count: ' + retCount); | ||||
|       if (retCount > 0) { | ||||
|         let asset = await assetsResult.getFirstObject(); | ||||
|         console.log('baoyihu queryPhotoByDisplayName one asset uri : ' + asset.uri + ', photoType : ' + | ||||
|         console.log(FileHelpTag, ' queryPhotoByDisplayName one asset uri : ' + asset.uri + ', photoType : ' + | ||||
|         asset.photoType + ', displayName : ' + asset.displayName); | ||||
|         console.log('baoyihu queryPhotoByDisplayName success '); | ||||
|         console.log(FileHelpTag, ' queryPhotoByDisplayName success '); | ||||
|       } | ||||
|     } catch (err) { | ||||
|       console.log('baoyihu queryPhotoByDisplayName failed with err: ' + err); | ||||
|       console.error(FileHelpTag, ' queryPhotoByDisplayName failed with err: ' + err); | ||||
|     } finally { | ||||
|     } | ||||
|   } | ||||
| @ -58,7 +59,7 @@ export class FileHelper { | ||||
|     let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.Album> = null | ||||
|     let album: photoAccessHelper.Album = null | ||||
|     try { | ||||
|       console.log('getUserAlbumItemByDisplayName'); | ||||
|       console.log(FileHelpTag, 'getUserAlbumItemByDisplayName'); | ||||
|       let predicates = new dataSharePredicates.DataSharePredicates(); | ||||
|       predicates.equalTo(photoAccessHelper.AlbumKeys.ALBUM_NAME, displayName) | ||||
|       let fetchOptions: photoAccessHelper.FetchOptions = { | ||||
| @ -68,12 +69,12 @@ export class FileHelper { | ||||
|       fetchResult = | ||||
|         await this.userFileMgr.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, | ||||
|           fetchOptions); | ||||
|       console.log('get getUserAlbumItemByDisplayName, count: ' + fetchResult.getCount()); | ||||
|       console.log(FileHelpTag, 'get getUserAlbumItemByDisplayName, count: ' + fetchResult.getCount()); | ||||
|       if (fetchResult.getCount() > 0) { | ||||
|         album = await fetchResult.getFirstObject(); | ||||
|       } | ||||
|     } catch (err) { | ||||
|       console.log('get Album fetchResult failed with err: ' + err); | ||||
|       console.error(FileHelpTag, 'get Album fetchResult failed with err: ' + err); | ||||
|     } finally { | ||||
|       if (fetchResult != null) { | ||||
|         fetchResult.close(); | ||||
| @ -83,7 +84,7 @@ export class FileHelper { | ||||
|   } | ||||
| 
 | ||||
|   public async addAssetToAlbum(albumName: string, file_uri: string) { | ||||
|     console.log('baoyihu addAssetToAlbum begin albumName ' + albumName + ', file_uri:' + file_uri); | ||||
|     console.log(FileHelpTag, ' addAssetToAlbum begin albumName ' + albumName + ', file_uri:' + file_uri); | ||||
|     try { | ||||
|       let album = await this.getUserAlbumItemByDisplayName(albumName); | ||||
|       let predicates = new dataSharePredicates.DataSharePredicates(); | ||||
| @ -96,19 +97,19 @@ export class FileHelper { | ||||
| 
 | ||||
|       if (assetsResult.getCount() > 0) { | ||||
|         let asset = await assetsResult.getFirstObject(); | ||||
|         console.log('baoyihu addAssetToAlbum one asset uri : ' + asset.uri + ', photoType : ' + asset.photoType + | ||||
|         console.log(FileHelpTag, ' addAssetToAlbum one asset uri : ' + asset.uri + ', photoType : ' + asset.photoType + | ||||
|           ', displayName : ' + asset.displayName); | ||||
|         await album.addAssets([asset]); | ||||
|         console.log('baoyihu addAssetToAlbum success '); | ||||
|         console.log(FileHelpTag, ' addAssetToAlbum success '); | ||||
|       } | ||||
|     } catch (err) { | ||||
|       console.log('baoyihu addAssetToAlbum failed with err: ' + err); | ||||
|       console.error(FileHelpTag, ' addAssetToAlbum failed with err: ' + err); | ||||
|     } finally { | ||||
|     } | ||||
|   } | ||||
| 
 | ||||
|   public async deleteFileOfAlbum(album_Name: string, file_type: number | string | boolean): Promise<void> { | ||||
|     console.log('baoyihu deletePictureOfAlbum album_Name:' + album_Name); | ||||
|     console.log(FileHelpTag, ' deletePictureOfAlbum album_Name:' + album_Name); | ||||
|     let photoFetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = null; | ||||
|     try { | ||||
|       let album = await this.getUserAlbumItemByName(album_Name); | ||||
| @ -122,10 +123,10 @@ export class FileHelper { | ||||
|       let all_fileAsset = await photoFetchResult.getAllObjects(); | ||||
| 
 | ||||
|       let uri_array: string[] = [] | ||||
|       console.log('baoyihu deletePictureOfAlbum iterator begin', album_Name); | ||||
|       console.log(FileHelpTag, ' deletePictureOfAlbum iterator begin', album_Name); | ||||
|       for (let onfile of all_fileAsset) { | ||||
|         console.log(album_Name, | ||||
|           'baoyihu deletePictureOfAlbum uri : ' + onfile.uri + ', photoType : ' + onfile.photoType + | ||||
|         console.log(FileHelpTag, album_Name, | ||||
|           ' deletePictureOfAlbum uri : ' + onfile.uri + ', photoType : ' + onfile.photoType + | ||||
|             ', displayName : ' + onfile.displayName); | ||||
|         uri_array.push(onfile.uri); | ||||
|       } | ||||
| @ -138,21 +139,21 @@ export class FileHelper { | ||||
| 
 | ||||
|         let trashAlbum = await albumFetchResult.getFirstObject(); | ||||
|         trashAlbum.deleteAssets(all_fileAsset).then(() => { | ||||
|           console.log('baoyihu deletePictureOfAlbum trash ok : ', album_Name); | ||||
|           console.log(FileHelpTag, ' deletePictureOfAlbum trash ok : ', album_Name); | ||||
|         }).catch((err: BusinessError) => { | ||||
|           console.log('baoyihu deletePictureOfAlbum trash faild : ', album_Name); | ||||
|           console.error(FileHelpTag, ' deletePictureOfAlbum trash faild : ', album_Name, JSON.stringify(err)); | ||||
|         }); | ||||
|       } catch (err) { | ||||
|         console.log('baoyihu deletePictureOfAlbum error: ' + err, album_Name); | ||||
|         console.error(FileHelpTag, ' deletePictureOfAlbum error: ' + err, album_Name); | ||||
|       } finally { | ||||
|         if (albumFetchResult != null) { | ||||
|           albumFetchResult.close(); | ||||
|         } | ||||
|       } | ||||
| 
 | ||||
|       console.log('baoyihu deletePictureOfAlbum delete end', album_Name); | ||||
|       console.log(FileHelpTag, ' deletePictureOfAlbum delete end', album_Name); | ||||
|     } catch (err) { | ||||
|       console.log('baoyihu deletePictureOfAlbum failed with err: ' + err, album_Name); | ||||
|       console.error(FileHelpTag, ' deletePictureOfAlbum failed with err: ' + err, album_Name); | ||||
|     } finally { | ||||
|       if (photoFetchResult != null) { | ||||
|         photoFetchResult.close(); | ||||
| @ -161,7 +162,7 @@ export class FileHelper { | ||||
|   } | ||||
| 
 | ||||
|   public async deleteAllPictures(): Promise<void> { | ||||
|     console.log('baoyihu deleteAllPictures'); | ||||
|     console.log(FileHelpTag, ' deleteAllPictures'); | ||||
|     let photoFetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = null; | ||||
|     try { | ||||
|       let predicates = new dataSharePredicates.DataSharePredicates(); | ||||
| @ -173,15 +174,15 @@ export class FileHelper { | ||||
| 
 | ||||
|       let all_fileAsset = await photoFetchResult.getAllObjects(); | ||||
|       let uri_array: string[] = [] | ||||
|       console.log('baoyihu batch delete begin'); | ||||
|       console.log(FileHelpTag, ' batch delete begin'); | ||||
|       for (let onfile of all_fileAsset) { | ||||
|         uri_array.push(onfile.uri); | ||||
|       } | ||||
|       // await album.removeAssets(all_fileAsset); | ||||
|       await this.userFileMgr.deleteAssets(uri_array); | ||||
|       console.log('baoyihu batch delete end'); | ||||
|       console.log(FileHelpTag, ' batch delete end'); | ||||
|     } catch (err) { | ||||
|       console.log('baoyihu get Album getPhotoAssets failed with err: ' + err); | ||||
|       console.error(FileHelpTag, ' get Album getPhotoAssets failed with err: ' + err); | ||||
|     } finally { | ||||
|       if (photoFetchResult != null) { | ||||
|         photoFetchResult.close(); | ||||
| @ -220,7 +221,7 @@ export class FileHelper { | ||||
|     let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.Album> = null | ||||
|     let album: photoAccessHelper.Album = null | ||||
|     try { | ||||
|       console.log('getUserAlbumItemByName'); | ||||
|       console.log(FileHelpTag, 'getUserAlbumItemByName'); | ||||
|       let predicates = new dataSharePredicates.DataSharePredicates(); | ||||
|       predicates.equalTo(photoAccessHelper.AlbumKeys.ALBUM_NAME, albumName) | ||||
|       let fetchOptions: photoAccessHelper.FetchOptions = { | ||||
| @ -230,13 +231,13 @@ export class FileHelper { | ||||
|       fetchResult = | ||||
|         await this.userFileMgr.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, | ||||
|           fetchOptions); | ||||
|       console.log('get getUserAlbumItemByName, count: ' + fetchResult.getCount()); | ||||
|       console.log(FileHelpTag, 'get getUserAlbumItemByName, count: ' + fetchResult.getCount()); | ||||
|       if (fetchResult.getCount() > 0) { | ||||
|         album = await fetchResult.getFirstObject(); | ||||
|         console.log('getUserAlbumItemByName uri: ' + album.albumUri + ',albumName: ' + album.albumName); | ||||
|         console.log(FileHelpTag, 'getUserAlbumItemByName uri: ' + album.albumUri + ',albumName: ' + album.albumName); | ||||
|       } | ||||
|     } catch (err) { | ||||
|       console.log('getUserAlbumItemByName failed with err: ' + err); | ||||
|       console.error(FileHelpTag, 'getUserAlbumItemByName failed with err: ' + err); | ||||
|     } finally { | ||||
|       if (fetchResult != null) { | ||||
|         fetchResult.close(); | ||||
| @ -248,15 +249,15 @@ export class FileHelper { | ||||
| 
 | ||||
|   public async createAlbum(albumName: string): Promise<string> { | ||||
|     try { | ||||
|       console.log("baoyihu createAlbum beging"); | ||||
|       console.log(FileHelpTag, " createAlbum beging"); | ||||
|       let albumAsset = await this.userFileMgr.createAlbum(albumName); | ||||
|       console.log('baoyihu createAlbum success, albumType: ' + albumAsset.albumType + ', albumSubtype: ' + | ||||
|       console.log(FileHelpTag, ' createAlbum success, albumType: ' + albumAsset.albumType + ', albumSubtype: ' + | ||||
|       albumAsset.albumSubtype | ||||
|         + ', albumName: ' + albumAsset.albumName + ', albumUri: ' + albumAsset.albumUri + ', coverUri: ' + | ||||
|       albumAsset.coverUri); | ||||
|       return albumAsset.albumUri; | ||||
|     } catch (err) { | ||||
|       console.log('baoyihu createAlbum failed with err: ' + err); | ||||
|       console.error(FileHelpTag, ' createAlbum failed with err: ' + err); | ||||
|     } finally { | ||||
|     } | ||||
|   } | ||||
| @ -264,7 +265,7 @@ export class FileHelper { | ||||
| 
 | ||||
|   public async createPhotoAsset(type: photoAccessHelper.AlbumType, | ||||
|     subType: photoAccessHelper.AlbumSubtype): Promise<void> { | ||||
|     console.log('baoyihu createPhotoAsset enter '); | ||||
|     console.log(FileHelpTag, ' createPhotoAsset enter '); | ||||
|     try { | ||||
|       let createOptions: photoAccessHelper.PhotoCreateOptions = { subtype: photoAccessHelper.PhotoSubtype.SCREENSHOT }; | ||||
|       await this.userFileMgr.createAsset("picture2.jpg", createOptions, (err, photoResult) => { | ||||
| @ -272,7 +273,7 @@ export class FileHelper { | ||||
|           + ', displayName: ' + photoResult.displayName); | ||||
|       }); | ||||
|     } catch (err) { | ||||
|       console.log('baoyihu createPhotoAsset failed with err: ' + err); | ||||
|       console.error(FileHelpTag, ' createPhotoAsset failed with err: ' + err); | ||||
|     } finally { | ||||
|     } | ||||
|   } | ||||
| @ -283,11 +284,13 @@ export class FileHelper { | ||||
|     let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.Album> = null; | ||||
|     try { | ||||
|       fetchResult = await this.userFileMgr.getAlbums(type, subType); | ||||
|       console.log('baoyihu queryAlbum success count: ' + fetchResult.getCount()); | ||||
|       console.log(FileHelpTag, ' queryAlbum success count: ' + fetchResult.getCount()); | ||||
|       for (let i = 0; i < fetchResult.getCount(); i++) { | ||||
|         let albumAsset: photoAccessHelper.Album = await fetchResult.getObjectByPosition(i); | ||||
|         console.log('queryAlbum albumType: ' + albumAsset.albumType + ', Subtype: ' + albumAsset.albumSubtype | ||||
|           + ', Name: ' + albumAsset.albumName + ', Uri: ' + albumAsset.albumUri + ', coverUri: ' + albumAsset.coverUri); | ||||
|         console.log(FileHelpTag, | ||||
|           'queryAlbum albumType: ' + albumAsset.albumType + ', Subtype: ' + albumAsset.albumSubtype | ||||
|             + ', Name: ' + albumAsset.albumName + ', Uri: ' + albumAsset.albumUri + ', coverUri: ' + | ||||
|           albumAsset.coverUri); | ||||
| 
 | ||||
|         let predicates = new dataSharePredicates.DataSharePredicates(); | ||||
|         let fetchOptions: photoAccessHelper.FetchOptions = { | ||||
| @ -296,28 +299,28 @@ export class FileHelper { | ||||
|         }; | ||||
|         let photoFetchResult = await albumAsset.getAssets(fetchOptions); | ||||
|         let count = photoFetchResult.getCount(); | ||||
|         console.log('baoyihu queryAlbum photoFetchResult count: ' + count); | ||||
|         console.log(FileHelpTag, ' queryAlbum photoFetchResult count: ' + count); | ||||
|         let all_fileAsset = await photoFetchResult.getAllObjects(); | ||||
|         // var uri_array=[] | ||||
| 
 | ||||
|         for (let onfile of all_fileAsset) { | ||||
|           console.log('baoyihu queryAlbum one uri : ' + onfile.uri); | ||||
|           console.log(FileHelpTag, ' queryAlbum one uri : ' + onfile.uri); | ||||
|           firstUri = onfile.uri; | ||||
|           // uri_array.push(onfile.uri); | ||||
|         } | ||||
| 
 | ||||
|       } | ||||
|       console.log('baoyihu queryAlbum return asser:' + firstUri); | ||||
|       console.log(FileHelpTag, ' queryAlbum return asser:' + firstUri); | ||||
| 
 | ||||
|     } catch (err) { | ||||
|       console.log('baoyihu queryAlbum failed with err: ' + err); | ||||
|       console.error(FileHelpTag, ' queryAlbum failed with err: ' + err); | ||||
|     } finally { | ||||
|       if (fetchResult != null) { | ||||
|         fetchResult.close(); | ||||
|       } | ||||
|     } | ||||
|     return new Promise((resolve, reject) => { | ||||
|       console.log('baoyihu queryAlbum before resolve:' + firstUri); | ||||
|       console.log(FileHelpTag, ' queryAlbum before resolve:' + firstUri); | ||||
|       resolve(firstUri) | ||||
|     }) | ||||
| 
 | ||||
| @ -328,12 +331,12 @@ export class FileHelper { | ||||
|     let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.Album> = null; | ||||
|     try { | ||||
|       fetchResult = await this.userFileMgr.getAlbums(type, subType); | ||||
|       console.log('baoyihu_ get Album fetchResult, count: ' + fetchResult.getCount()); | ||||
|       console.log(FileHelpTag, ' get Album fetchResult, count: ' + fetchResult.getCount()); | ||||
|       for (let i = 0; i < fetchResult.getCount(); i++) { | ||||
|         let albumAsset: photoAccessHelper.Album = await fetchResult.getObjectByPosition(i); | ||||
|         let photoFetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = null; | ||||
|         let count = 0; | ||||
|         console.log('baoyihu_ get one Album name : ' + albumAsset.albumName); | ||||
|         console.log(FileHelpTag, ' get one Album name : ' + albumAsset.albumName); | ||||
|         try { | ||||
|           let predicates = new dataSharePredicates.DataSharePredicates(); | ||||
|           let fetchOptions: photoAccessHelper.FetchOptions = { | ||||
| @ -343,7 +346,7 @@ export class FileHelper { | ||||
| 
 | ||||
|           photoFetchResult = await albumAsset.getAssets(fetchOptions); | ||||
|           count = photoFetchResult.getCount(); | ||||
|           console.log('baoyihu_ photoFetchResult count: ' + count); | ||||
|           console.log(FileHelpTag, ' photoFetchResult count: ' + count); | ||||
|           let all_fileAsset = await photoFetchResult.getAllObjects(); | ||||
|           /* | ||||
|           var uri_array=[] | ||||
| @ -357,9 +360,9 @@ export class FileHelper { | ||||
|           await albumAsset.removeAssets(all_fileAsset); | ||||
|           //await this.userFileMgr.deleteAssets(uri_array); | ||||
| 
 | ||||
|           console.log('baoyihu_ batch delete end'); | ||||
|           console.log(FileHelpTag, ' batch delete end'); | ||||
|         } catch (err) { | ||||
|           console.log('baoyihu_ get Album getPhotoAssets failed with err: ' + err); | ||||
|           console.error(FileHelpTag, ' get Album getPhotoAssets failed with err: ' + err); | ||||
|         } finally { | ||||
|           if (photoFetchResult != null) { | ||||
|             photoFetchResult.close(); | ||||
| @ -367,7 +370,7 @@ export class FileHelper { | ||||
|         } | ||||
|       } | ||||
|     } catch (err) { | ||||
|       console.log('baoyihu_ get Album fetchResult failed with err: ' + err); | ||||
|       console.error(FileHelpTag, ' get Album fetchResult failed with err: ' + err); | ||||
|     } finally { | ||||
|       if (fetchResult != null) { | ||||
|         fetchResult.close(); | ||||
|  | ||||
| @ -1,12 +1,9 @@ | ||||
| import common from "@ohos.app.ability.common" | ||||
| import Want from "@ohos.app.ability.Want" | ||||
| import fileAccess from "@ohos.file.fileAccess" | ||||
| import common from '@ohos.app.ability.common' | ||||
| import fs from '@ohos.file.fs' | ||||
| import abilityAccessCtrl, { Permissions } from "@ohos.abilityAccessCtrl" | ||||
| import promptAction from "@ohos.promptAction" | ||||
| import { FileTag } from "../config" | ||||
| 
 | ||||
| const LOG_TAG = '[file utils]' | ||||
| import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl' | ||||
| import promptAction from '@ohos.promptAction' | ||||
| import { FileTag } from '../config' | ||||
| import { BusinessError } from '@ohos.base' | ||||
| 
 | ||||
| 
 | ||||
| export default class FileUtils { | ||||
| @ -17,134 +14,101 @@ export default class FileUtils { | ||||
| 
 | ||||
|   constructor(context: common.UIAbilityContext) { | ||||
|     this.context = context | ||||
|     this.requestPermission(); | ||||
|     this.requestPermission() | ||||
|     fs.mkdir(this.absolutePath) | ||||
|   } | ||||
| 
 | ||||
|   async initFolder(folderPath: string): Promise<string> { | ||||
|     const folderList = folderPath.split('/').filter(folderName => folderName !== ''); | ||||
|     const folderList = folderPath.split('/').filter(folderName => folderName !== '') | ||||
|     let path = this.absolutePath | ||||
|     folderList.forEach(folderName => { | ||||
|       path += `/${folderName}`; | ||||
|     for (const folderName of folderList) { | ||||
|       path += `/${folderName}` | ||||
|       try { | ||||
|         const isExit = fs.accessSync(path); | ||||
|         if (!isExit) { | ||||
|         if (!fs.accessSync(path)) { | ||||
|           fs.mkdirSync(path) | ||||
|         } | ||||
|       } catch (e) { | ||||
|         console.info('初始化文件夹失败', path) | ||||
|         promptAction.showToast({ | ||||
|           message: `初始化文件夹失败` + folderPath + JSON.stringify(e), | ||||
|           duration: 4000, | ||||
|         }) | ||||
|         this.handleError('初始化文件夹失败', e, folderPath) | ||||
|       } | ||||
|     }) | ||||
|     } | ||||
|     return path | ||||
|   } | ||||
| 
 | ||||
|   async addFile(filePath: string, content: string) { | ||||
|   async addFile(filePath: string, content: string): Promise<boolean> { | ||||
|     try { | ||||
|       //文件存在先删除 | ||||
|       if (fs.accessSync(filePath)) { | ||||
|         fs.unlinkSync(filePath); | ||||
|         fs.unlinkSync(filePath) | ||||
|       } | ||||
|       let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); | ||||
|       //追加写入文件 | ||||
|       const file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE) | ||||
|       fs.writeSync(file.fd, content) | ||||
|       fs.closeSync(file) | ||||
|       console.error(LOG_TAG, '写入文件成功') | ||||
|       console.log(FileTag, '写入文件成功') | ||||
|       return true | ||||
|     } catch (e) { | ||||
|       promptAction.showToast({ | ||||
|         message: `addFile文件失败` + filePath + JSON.stringify(e), | ||||
|         duration: 4000, | ||||
|       }) | ||||
|       console.error(LOG_TAG, '写入失败', JSON.stringify(e)) | ||||
|       this.handleError('写入失败', e, filePath) | ||||
|       return false | ||||
|     } | ||||
|   } | ||||
| 
 | ||||
|   async editFile(filePath: string, content: string, fd?: number) { | ||||
|     const thisFile: fs.File = this.filePathFdObj[filePath]; | ||||
|   async editFile(filePath: string, content: string): Promise<number | undefined> { | ||||
|     try { | ||||
|       if (thisFile) { | ||||
|         fs.writeSync(thisFile.fd, content + '\n') | ||||
|         return fd; | ||||
|       } else { | ||||
|         let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.APPEND | fs.OpenMode.CREATE); | ||||
|         fs.writeSync(file.fd, content + '\n') | ||||
|         this.filePathFdObj[filePath] = file | ||||
|         return file.fd | ||||
|       } | ||||
|       const file = this.filePathFdObj[filePath] || | ||||
|       fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.APPEND | fs.OpenMode.CREATE) | ||||
|       fs.writeSync(file.fd, content + '\n') | ||||
|       this.filePathFdObj[filePath] = file | ||||
|       return file.fd | ||||
|     } catch (e) { | ||||
|       promptAction.showToast({ | ||||
|         message: `editFile文件失败` + filePath + JSON.stringify(e), | ||||
|         duration: 4000, | ||||
|       }) | ||||
|       console.error(LOG_TAG, JSON.stringify(e)) | ||||
|       this.handleError('editFile文件失败', e, filePath) | ||||
|     } | ||||
|   } | ||||
| 
 | ||||
|   async readFile(filePath: string): Promise<string> { | ||||
|     try { | ||||
|       const str = await fs.readText(filePath); | ||||
|       return str | ||||
|       return await fs.readText(filePath) | ||||
|     } catch (e) { | ||||
|       promptAction.showToast({ | ||||
|         message: `读取文件失败` + filePath + JSON.stringify(e), | ||||
|         duration: 4000, | ||||
|       }) | ||||
|       console.log('readFile文件失败' + filePath + JSON.stringify(e)) | ||||
|       this.handleError('readFile文件失败', e, filePath) | ||||
|       return '' | ||||
|     } | ||||
|   } | ||||
| 
 | ||||
|   async closeFile(filePath: string) { | ||||
|     const thisFile = this.filePathFdObj[filePath]; | ||||
|     if (thisFile) { | ||||
|       fs.closeSync(thisFile); | ||||
|       console.info(FileTag, filePath + '文件关闭成功') | ||||
|   async closeFile(filePath: string): Promise<void> { | ||||
|     const file = this.filePathFdObj[filePath] | ||||
|     if (file) { | ||||
|       fs.closeSync(file) | ||||
|       console.log(FileTag, `${filePath}文件关闭成功`) | ||||
|     } | ||||
| 
 | ||||
|   } | ||||
| 
 | ||||
|   async getDeviceList(folderPath?: string) { | ||||
|   async getDeviceList(folderPath?: string): Promise<string[]> { | ||||
|     return this.getFilePathList(`${this.absolutePath}/${folderPath}`, false) | ||||
|   } | ||||
| 
 | ||||
|   async getFilePathList(filePath: string, isSdCard: boolean): Promise<string[]> { | ||||
|     let fileName: string[] = []; | ||||
|     let sdCardFileName: string[] = []; | ||||
| 
 | ||||
|     try { | ||||
|       const filenames = await fs.listFile(filePath); | ||||
|       for (let i = 0; i < filenames.length; i++) { | ||||
|         console.error(FileTag, `目录:${filePath}的子文件:${filenames[i]}`); | ||||
|         if (isSdCard) { | ||||
|           sdCardFileName.push(filenames[i]) | ||||
|         } else { | ||||
|           fileName.push(filenames[i]) | ||||
|         } | ||||
|       } | ||||
|       return isSdCard ? sdCardFileName : fileName | ||||
|       const filenames = await fs.listFile(filePath) | ||||
|       console.log(FileTag, `目录:${filePath}的子文件:${filenames.join(', ')}`) | ||||
|       return filenames | ||||
|     } catch (e) { | ||||
|       console.error(FileTag, JSON.stringify(e)); | ||||
|       this.handleError('获取文件列表失败', e, filePath) | ||||
|       return [] | ||||
|     } | ||||
|   } | ||||
| 
 | ||||
|   async deleteF(path: string, type: 1 | 2 | 3) { | ||||
|     if (type === 1) { | ||||
|       const fileList = await this.getFilePathList(`${this.absolutePath}/${path}`, false); | ||||
|       fileList.forEach((fileName) => { | ||||
|         fs.unlinkSync(`${this.absolutePath}/${path}/${fileName}`) | ||||
|       }) | ||||
|       fs.rmdirSync(`${this.absolutePath}/${path}`); | ||||
|       return true | ||||
|     } else if (type === 2) { | ||||
|       fs.unlinkSync(`${this.absolutePath}/${path}`); | ||||
|       return true | ||||
|     } else { | ||||
|       fs.unlinkSync(`${path}`); | ||||
|   async deleteF(path: string, type: 1 | 2 | 3): Promise<boolean> { | ||||
|     try { | ||||
|       if (type === 1) { | ||||
|         const fileList = await this.getFilePathList(`${this.absolutePath}/${path}`, false) | ||||
|         fileList.forEach(fileName => fs.unlinkSync(`${this.absolutePath}/${path}/${fileName}`)) | ||||
|         fs.rmdirSync(`${this.absolutePath}/${path}`) | ||||
|       } else if (type === 2) { | ||||
|         fs.unlinkSync(`${this.absolutePath}/${path}`) | ||||
|       } else { | ||||
|         fs.unlinkSync(path) | ||||
|       } | ||||
|       return true | ||||
|     } catch (e) { | ||||
|       this.handleError('删除文件失败', e, path) | ||||
|       return false | ||||
|     } | ||||
|   } | ||||
| 
 | ||||
| @ -152,28 +116,32 @@ export default class FileUtils { | ||||
|     return this.absolutePath | ||||
|   } | ||||
| 
 | ||||
|   getFileContent(filePath: string) { | ||||
|   getFileContent(filePath: string): string { | ||||
|     const path = `${this.absolutePath}/${filePath}` | ||||
|     const str = fs.readTextSync(path); | ||||
|     return str | ||||
|     return fs.readTextSync(path) | ||||
|   } | ||||
| 
 | ||||
| 
 | ||||
|   private async requestPermission() { | ||||
|     let permissions: Array<Permissions> = [ | ||||
|   private async requestPermission(): Promise<void> { | ||||
|     const permissions: Array<Permissions> = [ | ||||
|       'ohos.permission.READ_MEDIA', | ||||
|       'ohos.permission.WRITE_MEDIA' | ||||
|     ]; | ||||
|     let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager() | ||||
|     atManager.requestPermissionsFromUser(this.context, permissions, async (code, result) => { | ||||
|       const permissionRequest = result.authResults[0] | ||||
|       if (permissionRequest == -1) { | ||||
|     ] | ||||
|     const atManager = abilityAccessCtrl.createAtManager() | ||||
|     atManager.requestPermissionsFromUser(this.context, permissions, (code, result) => { | ||||
|       if (result.authResults[0] === -1) { | ||||
|         promptAction.showToast({ | ||||
|           message: "请先授权", | ||||
|           message: '请先授权', | ||||
|           duration: 3000, | ||||
|         }) | ||||
|         return | ||||
|       } | ||||
|     }) | ||||
|   } | ||||
| 
 | ||||
|   private handleError(message: string, error: BusinessError, filePath: string): void { | ||||
|     console.error(FileTag, `${message} ${filePath} ${JSON.stringify(error)}`) | ||||
|     promptAction.showToast({ | ||||
|       message: `${message} ${filePath} ${JSON.stringify(error)}`, | ||||
|       duration: 4000, | ||||
|     }) | ||||
|   } | ||||
| } | ||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user