android获取本地文件名字?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android获取本地文件名字?相关的知识,希望对你有一定的参考价值。

我在java里可以获取F:/0710 文件夹里的所有.txt文件===-===
但在android项目里却不可以?谁知道怎么解决吗?
===============-=======下面是java代码==============-=====================

在aaa类的main方法里 File file=new File("F:/0710");
new aaa().getFile(file);//给他个路径就打印出所有txt文件名了。。。

void getFile(File file)
File[] fs = file.listFiles();//从文件里读,读出的数组。
for (int i = 0; i < fs.length; i++) //遍历出所有文件。
File mf = fs[i]; //拿到每一个文件。
if (mf.isDirectory()) //如果不是文件,是文件夹。
getFile(mf); //则继续迭代。

//System.out.println("===="+mf);//打印出所有文件。
String name = mf.getName();//只打印文件,文件夹不打印出来。
//System.out.println("######"+name);//打印出所有文件不是全名的。
if(name.endsWith(".txt"))
// System.out.println("##=="+name);//打印出所有以.txt结尾的文件。
int length11 = name.length();
String name2 = name.substring(0,(length11-4));//去掉后缀名。
Log.e("===name2===", name2);//打印出所有无后最的文件名。





我写了个例子,你看能用吗?

package com.dragonred.android.utils;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.util.Log;

public final class FileUtils

public final static String PACKAGE_PATH = "com.dragonred.android";
// public final static String LOG_FILE_NAME = "smartprint.txt";
// public final static String LOG_FILE_PATH = STORE_DIRECTORY_PATH + File.separatorChar + LOG_FILE_NAME;

/**
* read key value from preference by key name
*
* @param context
* @param keyName
* @return
*/
public final static String readPreperence(Context context, String keyName)
SharedPreferences settings = context.getSharedPreferences(
PACKAGE_PATH, 0);
return settings.getString(keyName, "");


/**
* write key name and key value into preference
*
* @param context
* @param keyName
* @param keyValue
*/
public final static void writePreperence(Context context, String keyName,
String keyValue)
SharedPreferences settings = context.getSharedPreferences(
PACKAGE_PATH, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(keyName, keyValue);
editor.commit();


/**
* delete key from preference by key name
*
* @param context
* @param keyName
*/
public final static void deletePreperence(Context context, String keyName)
SharedPreferences settings = context.getSharedPreferences(
PACKAGE_PATH, 0);
SharedPreferences.Editor editor = settings.edit();

editor.remove(keyName);
editor.commit();


public final static String getContextFilePath(Context context, String fileName)
return context.getFilesDir().getAbsolutePath() + File.separatorChar + fileName;


public final static boolean existContextFile(Context context, String fileName)
String filePath = context.getFilesDir().getAbsolutePath() + File.separatorChar + fileName;
Log.d("filePath", filePath);

File file = new File(filePath);
if (file.exists())
return true;

return false;


public final static void saveContextFile(Context context, String fileName, String content) throws Exception
FileOutputStream outputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
outputStream.write(content.getBytes());
outputStream.close();


public final static void saveAppendContextFile(Context context, String fileName, String content) throws Exception
FileOutputStream outputStream = context.openFileOutput(fileName, Context.MODE_APPEND);
outputStream.write(content.getBytes());
outputStream.close();


public final static void deleteContextFile(Context context, String fileName) throws Exception
context.deleteFile(fileName);


public final static String readContextFile(Context context, String fileName) throws Exception
FileInputStream inputStream = context.openFileInput(fileName);
byte[] buffer = new byte[1024];
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int len = -1;
while ((len = inputStream.read(buffer)) != -1)
byteArrayOutputStream.write(buffer, 0, len);

byte[] data = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.close();
inputStream.close();
return new String(data);


/**
* delete file or folders
* @param file
*/
public final static void deleteFile(File file)
if (file.exists())
if (file.isFile())
file.delete();
else if (file.isDirectory())
File files[] = file.listFiles();
for (int i = 0; i < files.length; i++)
deleteFile(files[i]);


file.delete();
else
Log.d("deleteFile", "The file or directory does not exist!");



/**
* make directory on SD card
* @param dirPath
* @return
*/
public final static boolean makeDir(String dirPath)
File dir = new File(dirPath);
if(!dir.isDirectory())
if (dir.mkdirs())
return true;

else
return true;

return false;


/**
* write log file
* @param filePath
* @param tag
* @param content
*/
public final static void writeLog(String filePath, String tag, String content)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String logDateTime = sdf.format(new Date());
writeFileByAppend(filePath, logDateTime + "---[" + tag + "]---" + content + "\n");


/**
* write file by append mode
* @param filePath
* @param content
*/
public final static void writeFileByAppend(String filePath, String content)
// FileWriter writer = null;
// try
// writer = new FileWriter(filePath, true);
// writer.write(content);
// catch (IOException e)
// e.printStackTrace();
// finally
// try
// writer.close();
// catch (IOException e)
// e.printStackTrace();
//
//
RandomAccessFile randomFile = null;
try
randomFile = new RandomAccessFile(filePath, "rw");
long fileLength = randomFile.length();
randomFile.seek(fileLength);
randomFile.write(content.getBytes());

catch (IOException e)
e.printStackTrace();
finally
try
randomFile.close();
catch (IOException e)
e.printStackTrace();


// BufferedWriter out = null;
// try
// out = new BufferedWriter(new OutputStreamWriter(
// new FileOutputStream(filePath, true), "UTF-8"));
// out.write(content);
// catch (Exception e)
// e.printStackTrace();
// finally
// try
// out.close();
// catch (IOException e)
// e.printStackTrace();
//
//



/**
* write file by overwrite mode
* @param filePath
* @param content
*/
public final static void writeFile(String filePath, String content)
// FileWriter writer = null;
// try
// writer = new FileWriter(filePath, true);
// writer.write(content);
// catch (IOException e)
// e.printStackTrace();
// finally
// try
// writer.close();
// catch (IOException e)
// e.printStackTrace();
//
//
BufferedWriter out = null;
try
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(filePath, false), "UTF-8"));
out.write(content);
catch (Exception e)
e.printStackTrace();
finally
try
out.close();
catch (IOException e)
e.printStackTrace();




/**
* check SD card whether or not exist
* @param context
* @return
*/
public final static boolean checkSDCard(Context context)
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState()))
return true;
else
// Toast.makeText(context, "Please check your SD card! ",
// Toast.LENGTH_SHORT).show();
return false;



/**
* read last line from file
* @param filePath
* @return
*/
public final static String readLastLinefromFile(String filePath)
RandomAccessFile raf = null;
try
File file = new File(filePath);
if (!file.exists())
return null;


raf = new RandomAccessFile(filePath, "r");
long len = raf.length();
if (len == 0L)
return "";
else
long pos = len - 1;
while (pos > 0)
pos--;
raf.seek(pos);
if (raf.readByte() == '\n')
break;


if (pos == 0)
raf.seek(0);

byte[] bytes = new byte[(int) (len - pos)];
raf.read(bytes);
return new String(bytes);

catch (Exception e)
e.printStackTrace();
finally
if (raf != null)
try
raf.close();
catch (Exception e2)



return null;

参考技术A 首先你的路径是否正确,第二查看是否有读权限(默认是有的)。除这两点无其他可能,遍历没区别。 参考技术B 哥哥你请的问题好深奥,无人能答。你悬赏浪费可惜,不如给我吧?本回答被提问者采纳

获取图片和下载到本地和名字和链接的获取

# -*- coding: utf-8 -*-
import urllib.request
import ssl
import json
import xlwt
context = ssl._create_unverified_context()

title=[女装,鞋包,男士,运动,饰品,美妆,母婴,居家,国际,生活]
wb = xlwt.Workbook()
class spider:
    def url_name(self):
        wb = xlwt.Workbook()
        for i in range(len(title)):
            list_name = []
            list_img = []
            print(i+1)
            ws = wb.add_sheet(title[i])
            url = http://www.vip.com/index-ajax.php?act=getSellingBrandListV5&warehouse=VIP_NH&areaCode=104104&channelId=0&pagecode=b&sortType=1&province_name=%E5%B9%BF%E4%B8%9C&city_name=%E5%B9%BF%E5%B7%9E%E5%B8%82&preview=&sell_time_from=&time_from=&ids=+str(i+1)
            url_data = urllib.request.urlopen(url).read().decode("utf-8")
            print(url_data)
            jsDict = json.loads(url_data)
            print(jsDict)
            jsdata = jsDict[data]
            jsfloor = jsdata[floors]
            jsfirst = jsfloor[str(i+1)]
            jsitems = jsfirst[items]
            for each in jsitems:
                list_img.append(each[mobile_image_one])
                list_name.append(each[name])
            print(len(list_img))
            print(len(list_name))
            print(list_name)
            print(list_img)
            for each in range(len(list_name)):
                ws.write(each, 0, list_name[each])
                ws.write(each, 1, list_img[each])
            x=0
            for j in list_img:
                urllib.request.urlretrieve(j, D:\\weipinhui\\monning_1\\jingxuan_pic\\+str(i+1)+\\%s.jpg % x)
                x = x + 1
            wb.save(D:\\weipinhui\\monning_1\\jingxuan_name_url\\jingxuan_name_url.xls)
    def shouye(self):
        wb = xlwt.Workbook()
        ws = wb.add_sheet(首页)
        list_name_sy=[]
        list_img_sy=[]
        url = http://pcapi.vip.com/ads/index.php?callback=shopAds&type=ADSEC56K%2CADSIR7IX%2CADSX7W3G%2CADSNNLS7%2CADS7JI3F%2CADS2B669%2CADSITG64%2CADS45AV4%2CADS44T33&warehouse=VIP_NH&areaid=104104&preview=0&date_from=&time_from=&user_class=&channelId=0
        url_data = urllib.request.urlopen(url).read().decode("utf-8")
        url_data = url_data.replace(shopAds(, ‘‘)
        url_data = url_data.replace(), ‘‘)
        jsDict = json.loads(url_data)
        print(jsDict)
        jsdata = jsDict[ADADSEC56K]
        jsdatas = jsdata[items]
        for each in jsdatas:
            list_name_sy.append(each[name])
            list_img_sy.append(each[img])
        print(list_img_sy)
        print(list_name_sy)
        x = 0
        for each in range(len(list_name_sy)):
            ws.write(each, 0, list_name_sy[each])
            ws.write(each, 1, list_img_sy[each])
        for j in list_img_sy:
            urllib.request.urlretrieve(j, D:\\weipinhui\\monning_1\\shouye_pic\\%s.jpg % x)
            x = x + 1
        wb.save(D:\\weipinhui\\monning_1\\shouye_name_url\\shouye_name_url.xls)
content=spider()
content.url_name()
content.shouye()

 

以上是关于android获取本地文件名字?的主要内容,如果未能解决你的问题,请参考以下文章

如何从浏览器获取本地存储在 Android 中的文件列表?

使用改造从(本地)android资产文件夹获取Json数据

Android读取本地json文件的方法

Android Studio开发获取本地时间

Android本地化xml文件

在 Android 中解析本地 XML 文件