Android U 디스크 읽기 및 쓰기
android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
android:name="android.permission.READ_EXTERNAL_STORAGE"/>
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
android:name="android.hardware.usb.host"
android:required="false" />
android:name="android.hardware.usb.host"
android:required="true" />
그 다음에 U-디스크 읽기와 쓰기 작업에 대한 의존 패키지를 추가합니다. 저도 모두가 추천하는 것을 사용합니다.
compile 'com.github.mjdev:libaums:0.5.5'
계속 코드: 우선 쓰기 (주의: 당신의 핸드폰 루트가 필요합니다)
1단계: 브로드캐스트 등록
/**
* @description OTG
* @author ldm
* @time 2017/9/1 17:19
*/
private void registerUDiskReceiver() {
// otg
IntentFilter usbDeviceStateFilter = new IntentFilter();
usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
registerReceiver(mOtgReceiver, usbDeviceStateFilter);
//
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mOtgReceiver, filter);
}
/**
* @description OTG , U
* @author ldm
* @time 2017/9/1 17:20
* @param
*/
private BroadcastReceiver mOtgReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
switch (action) {
case ACTION_USB_PERMISSION://
usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
//
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (usbDevice != null) {
// ,
readDevice(getUsbMass(usbDevice));
} else {
showToastMsg(" U ");
}
} else {
showToastMsg(" U ");
}
break;
case UsbManager.ACTION_USB_DEVICE_ATTACHED:// U
UsbDevice device_add = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device_add != null) {
// U , U
redUDiskDevsList();
}
break;
case UsbManager.ACTION_USB_DEVICE_DETACHED:// U
showToastMsg("U ");
break;
}
}
};
장치 읽기
/**
* @description U
* @author ldm
* @time 2017/9/1 17:20
*/
private void redUDiskDevsList() {
//
UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
// U
storageDevices = UsbMassStorageDevice.getMassStorageDevices(this);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
// 1 OTG
for (UsbMassStorageDevice device : storageDevices) {
//
if (usbManager.hasPermission(device.getUsbDevice())) {
readDevice(device);
} else {
// ,
usbManager.requestPermission(device.getUsbDevice(), pendingIntent);
}
}
if (storageDevices.length == 0) {
showToastMsg(" U ");
}
}
장치 쓰기:
/**
* @description U ,
* @author ldm
* @time 2017/9/1 17:17
*/
private void saveText2UDisk(String content) {
// SD , U
File file = FileUtil.getSaveFile(getPackageName()
+ File.separator + FileUtil.DEFAULT_BIN_DIR,
U_DISK_FILE_NAME);
try {
FileWriter fw = new FileWriter(file);
fw.write(content);
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
if (null != cFolder) {
FileUtil.saveSDFile2OTG(MainActivity.this,file, cFolder);
mHandler.sendEmptyMessage(100);
}
}
파일 작업 클래스:
public class FileUtil {
public static final String DEFAULT_BIN_DIR = "usb";
/**
* SD
*/
public static boolean checkSDcard() {
return Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState());
}
/**
*
*
* @return , null
*/
public static File getSaveFile(String folderPath, String fileNmae) {
File file = new File(getSavePath(folderPath) + File.separator
+ fileNmae);
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
/**
* SD
*
* @return SD
*/
public static String getSavePath(String folderName) {
return getSaveFolder(folderName).getAbsolutePath();
}
/**
*
*
* @return SD ,
*/
public static File getSaveFolder(String folderName) {
File file = new File(getExternalStorageDirectory()
.getAbsoluteFile()
+ File.separator
+ folderName
+ File.separator);
file.mkdirs();
return file;
}
/**
*
*/
public static void closeIO(Closeable... closeables) {
if (null == closeables || closeables.length <= 0) {
return;
}
for (Closeable cb : closeables) {
try {
if (null == cb) {
continue;
}
cb.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void redFileStream(OutputStream os, InputStream is) throws IOException {
int bytesRead = 0;
byte[] buffer = new byte[1024 * 8];
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.flush();
os.close();
is.close();
}
public static List getAllExterSdcardPath()
{
List SdList = new ArrayList();
String firstPath = Environment.getExternalStorageDirectory().getPath();
try
{
Runtime runtime = Runtime.getRuntime();
// mount , ,
Process proc = runtime.exec("mount");
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
String line;
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null)
{
Log.d("", line);
// linux
if (line.contains("proc") || line.contains("tmpfs") || line.contains("media") || line.contains("asec") || line.contains("secure") || line.contains("system") || line.contains("cache")
|| line.contains("sys") || line.contains("data") || line.contains("shell") || line.contains("root") || line.contains("acct") || line.contains("misc") || line.contains("obb"))
{
continue;
}
//
if (line.contains("fat") || line.contains("fuse") || (line.contains("ntfs")))
{
// mount ,items[0] ,items[1]
String items[] = line.split(" ");
if (items != null && items.length > 1)
{
String path = items[1].toLowerCase(Locale.getDefault());
// , sd , otg ,
if (path != null && !SdList.contains(path) && path.contains("sd"))
SdList.add(items[1]);
}
}
}
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
if (!SdList.contains(firstPath))
{
SdList.add(firstPath);
}
return SdList;
}
/**
* @description U
* @author ldm
* @time 2017/8/22 10:22
*/
public static void saveSDFile2OTG(Context context,final File f, final UsbFile usbFile) {
UsbFile uFile = null;
FileInputStream fis = null;
try {//
fis = new FileInputStream(f);//
if (usbFile.isDirectory()) {//
UsbFile[] usbFiles = usbFile.listFiles();
if (usbFiles != null && usbFiles.length > 0) {
for (UsbFile file : usbFiles) {
if (file.getName().equals(f.getName())) {
file.delete();
}
}
}
uFile = usbFile.createFile(f.getName());
UsbFileOutputStream uos = new UsbFileOutputStream(uFile);
try {
redFileStream(uos, fis);
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (final Exception e) {
e.printStackTrace();
Toast.makeText(context,e.toString(),Toast.LENGTH_LONG).show();
}
}
}
private final static String U_DISK_FILE_NAME = "****.txt";//
읽기 조작:Ps:처음엔 쉬울 줄 알았는데 나중에는 그렇게 간단하지 않았어요.
UsbDevice 가져오기
private UsbMassStorageDevice getUsbMass(UsbDevice usbDevice) {
if(usbDevice!=null){
for (UsbMassStorageDevice device : storageDevices) {
if (usbDevice.equals(device.getUsbDevice())) {
return device;
}
}
}
return null;
}
초기화 호출:
private void readDevice(UsbMassStorageDevice device) {
try {
device.init();//
//
Partition partition = device.getPartitions().get(0);
//
currentFs = partition.getFileSystem();
currentFs.getVolumeLabel();//
// FileSystem U , ,
Log.e("Capacity: ", currentFs.getCapacity() + "");
Log.e("Occupied Space: ", currentFs.getOccupiedSpace() + "");
Log.e("Free Space: ", currentFs.getFreeSpace() + "");
Log.e("Chunk size: ", currentFs.getChunkSize() + "");
cFolder = currentFs.getRootDirectory();//
UsbFile[] usbFiles=cFolder.listFiles();
if (null != usbFiles && usbFiles.length > 0) {
for (UsbFile usbFile : usbFiles) {
if (usbFile.getName().equals(U_DISK_FILE_NAME)) {
readFile(usbFile);
// readTxtFromUDisk(usbFile);
}
}
}
} catch (Exception e) {
e.printStackTrace();
android.widget.Toast.makeText(AddPwsAddressActivity.this,e.toString(), android.widget.Toast.LENGTH_LONG).show();
}
}
private void readFile(final UsbFile uFile) {
String sdPath = SDUtils.getSDPath();// sd
String filePath = sdPath + "/" + uFile.getName();
final File f = new File(filePath);
if (!f.exists()) {
try {
f.createNewFile();
//
//
executorService.execute(new Runnable() {
@Override
public void run() {
try {
FileOutputStream os = new FileOutputStream(f);
InputStream is = new UsbFileInputStream(uFile);
final String bt = redFileStream(os, is);
runOnUiThread(new Runnable() {
@Override
public void run() {
android.widget.Toast.makeText(AddPwsAddressActivity.this,bt, android.widget.Toast.LENGTH_LONG).show();
Message msg = mHandler.obtainMessage();
msg.what = 101;
android.widget.Toast.makeText(AddPwsAddressActivity.this,bt, android.widget.Toast.LENGTH_LONG).show();
msg.obj = bt;
mHandler.sendMessage(msg);
}
});
} catch (final Exception e) {
e.printStackTrace();
}
}
});
} catch (final Exception e) {
e.printStackTrace();
}
}else {
try {
executorService.execute(new Runnable() {
@Override
public void run() {
try {
FileOutputStream os = new FileOutputStream(f);
InputStream is = new UsbFileInputStream(uFile);
final String bt = redFileStream(os, is);
runOnUiThread(new Runnable() {
@Override
public void run() {
android.widget.Toast.makeText(AddPwsAddressActivity.this,bt, android.widget.Toast.LENGTH_LONG).show();
Message msg = mHandler.obtainMessage();
msg.what = 101;
android.widget.Toast.makeText(AddPwsAddressActivity.this,bt, android.widget.Toast.LENGTH_LONG).show();
msg.obj = bt;
mHandler.sendMessage(msg);
}
});
} catch (final Exception e) {
e.printStackTrace();
}
}
});
} catch (final Exception e) {
e.printStackTrace();
}
}
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 100:
showToastMsg(" ");
break;
case 101:
if(msg.obj==null){
Toast.makeText(MainActivity.this," ",Toast.LENGTH_LONG).show();
}else{
String txt = msg.obj.toString();
if (!TextUtils.isEmpty(txt))
u_disk_show.setText(" :" + txt);
}
break;
}
}
};
Ps:반등록 방송 잊지 마세요.
특히 감사합니다.
https://blog.csdn.net/csdn635406113/article/details/70146041
https://blog.csdn.net/true100/article/details/77775700
그리고 제 친구 원숭이의 사심 없는 공유에 감사합니다~
sd 카드 도구 클래스:
public class SDUtils {
private static final String TAG = " ";
public static String getSDPath() {
File sdDir = null;
boolean sdCardExist = Environment.getExternalStorageState()
.equals(Environment.MEDIA_MOUNTED); // sd
if (sdCardExist) {
sdDir = Environment.getExternalStorageDirectory();//
// sdDir1 = Environment.getDataDirectory();
// sdDir2 = Environment.getRootDirectory();
} else {
Log.d(TAG, "getSDPath: sd ");
}
Log.d(TAG, "getSDPath: " + sdDir.getAbsolutePath());
return sdDir.getAbsolutePath();
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.