1# Accessing Files Across Devices 2<!--Kit: Core File Kit--> 3<!--Subsystem: FileManagement--> 4<!--Owner: @wang_zhangjun; @zhuangzhuang--> 5<!--Designer: @wang_zhangjun; @zhuangzhuang; @renguang1116--> 6<!--Tester: @liuhonggang123; @yue-ye2; @juxiaopang--> 7<!--Adviser: @foryourself--> 8 9The distributed file system provides applications the capability for accessing files across devices. If the same application has been installed on two devices, you can use the [ohos.file.fs APIs](app-file-access.md) to read and write the application files in the [distributed file directory](app-sandbox-directory.md#mappings-between-application-sandbox-paths-and-physical-paths) (**/data/storage/el2/distributedfiles/**) on the other device. For example, an application is installed on both device A and device B. After device A and device B are connected to form a Super Device, the application on device A can access the files in the distributed directory of the same application on device B. 10 11## How to Develop 12 131. Connect the devices to form a Super Device.<br> 14 Log in to the same account on two devices and ensure that Bluetooth and Wi-Fi are enabled. Bluetooth does not require a physical connection, and Wi-Fi does not need to be connected to the same LAN. 15 162. Grant the distributed data synchronization permission. 17 Use **requestPermissionsFromUser** to request user authorization for the ohos.permission.DISTRIBUTED_DATASYNC permission in the form of a dialog box. For details about how to obtain the application context, see [Obtaining the Context of UIAbility](../application-models/uiability-usage.md#obtaining-the-context-of-uiability). 18 19 ```ts 20 import { common, abilityAccessCtrl } from '@kit.AbilityKit'; 21 import { BusinessError } from '@kit.BasicServicesKit'; 22 // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. 23 let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 24 let atManager = abilityAccessCtrl.createAtManager(); 25 try { 26 // Request the permission from users in the form of a dialog box. 27 atManager.requestPermissionsFromUser(context, ['ohos.permission.DISTRIBUTED_DATASYNC']).then((result) => { 28 console.info(`request permission result: ${JSON.stringify(result)}`); 29 }).catch((err: BusinessError) => { 30 console.error(`Failed to request permissions from user. Code: ${err.code}, message: ${err.message}`); 31 }) 32 } catch (error) { 33 let err: BusinessError = error as BusinessError; 34 console.error(`Catch err. Failed to request permissions from user. Code: ${err.code}, message: ${err.message}`); 35 } 36 ``` 37 383. Implement cross-device access to the files of your application.<br> 39 Place the files in the **distributedfiles/** directory of the application sandbox directory to implement access from difference devices. 40 41 For example, create a file in the **distributedfiles/** directory on device A and write data to the file. For details about how to obtain the application context, see [Obtaining the Context of UIAbility](../application-models/uiability-usage.md#obtaining-the-context-of-uiability). 42 43 ```ts 44 import { fileIo as fs } from '@kit.CoreFileKit'; 45 import { common } from '@kit.AbilityKit'; 46 import { BusinessError } from '@kit.BasicServicesKit'; 47 48 // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. 49 let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 50 let pathDir: string = context.distributedFilesDir; 51 // Obtain the file path of the distributed directory. 52 let filePath: string = pathDir + '/test.txt'; 53 54 try { 55 // Create a file in the distributed directory. 56 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 57 console.info('Succeeded in creating.'); 58 // Write data to the file. 59 fs.writeSync(file.fd, 'content'); 60 // Close the file. 61 fs.closeSync(file.fd); 62 } catch (error) { 63 let err: BusinessError = error as BusinessError; 64 console.error(`Failed to openSync / writeSync / closeSync. Code: ${err.code}, message: ${err.message}`); 65 } 66 ``` 67 68 Device B initiates a link setup request to device A. After the link is set up, device B can read the test file in the distributed file directory. 69 > **NOTE** 70 > 71 > The network ID (**networkId**) of the device can be obtained by using distributed device management APIs. For details, see [Device Management](../reference/apis-distributedservice-kit/js-apis-distributedDeviceManager.md). 72 73 ```ts 74 import { fileIo as fs } from '@kit.CoreFileKit'; 75 import { common } from '@kit.AbilityKit'; 76 import { BusinessError } from '@kit.BasicServicesKit'; 77 import { buffer } from '@kit.ArkTS'; 78 import { distributedDeviceManager } from '@kit.DistributedServiceKit'; 79 80 // Obtain the network ID of device A by calling distributed device management APIs. 81 let dmInstance = distributedDeviceManager.createDeviceManager("com.example.hap"); 82 let deviceInfoList: Array<distributedDeviceManager.DeviceBasicInfo> = dmInstance.getAvailableDeviceListSync(); 83 if (deviceInfoList && deviceInfoList.length > 0) { 84 console.info(`Success to get available device list`); 85 let networkId = deviceInfoList[0].networkId; 86 // Define the callback for accessing the user directory. 87 let listeners : fs.DfsListeners = { 88 onStatus: (networkId: string, status: number): void => { 89 console.info('Failed to access public directory'); 90 } 91 }; 92 // Start to access files cross devices. 93 fs.connectDfs(networkId, listeners).then(() => { 94 console.info("Success to connect dfs"); 95 // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. 96 let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 97 let pathDir: string = context.distributedFilesDir; 98 // Obtain the file path of the distributed directory. 99 let filePath: string = pathDir + '/test.txt'; 100 try { 101 // Open the file in the distributed directory. 102 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE); 103 // Set the buffer for receiving the read data. 104 let arrayBuffer = new ArrayBuffer(4096); 105 // Read the file. The return value is the number of read bytes. 106 class Option { 107 public offset: number = 0; 108 public length: number = 0; 109 }; 110 let option = new Option(); 111 option.length = arrayBuffer.byteLength; 112 let num = fs.readSync(file.fd, arrayBuffer, option); 113 // Print the read data. 114 let buf = buffer.from(arrayBuffer, 0, num); 115 console.info('read result: ' + buf.toString()); 116 fs.closeSync(file); 117 } catch (error) { 118 let err: BusinessError = error as BusinessError; 119 console.error(`Failed to openSync / readSync. Code: ${err.code}, message: ${err.message}`); 120 } 121 }).catch((error: BusinessError) => { 122 let err: BusinessError = error as BusinessError; 123 console.error(`Failed to connect dfs. Code: ${err.code}, message: ${err.message}`); 124 }); 125 } 126 ``` 127 1283. Disconnect the link for device B. 129 130 ```ts 131 import { BusinessError } from '@kit.BasicServicesKit'; 132 import { distributedDeviceManager } from '@kit.DistributedServiceKit'; 133 import { fileIo as fs } from '@kit.CoreFileKit'; 134 135 // Obtain the network ID of device A. 136 let dmInstance = distributedDeviceManager.createDeviceManager("com.example.hap"); 137 let deviceInfoList: Array<distributedDeviceManager.DeviceBasicInfo> = dmInstance.getAvailableDeviceListSync(); 138 if (deviceInfoList && deviceInfoList.length > 0) { 139 console.info(`Success to get available device list`); 140 let networkId = deviceInfoList[0].networkId; 141 // Disable cross-device file access. 142 fs.disconnectDfs(networkId).then(() => { 143 console.info("Success to disconnect dfs"); 144 }).catch((err: BusinessError) => { 145 console.error(`Failed to disconnect dfs. Code: ${err.code}, message: ${err.message}`); 146 }) 147 } 148 ``` 149