Подтвердить что ты не робот

Читать файл из активов

public class Utils {
    public static List<Message> getMessages() {
        //File file = new File("file:///android_asset/helloworld.txt");
        AssetManager assetManager = getAssets();
        InputStream ims = assetManager.open("helloworld.txt");    
     }
}

Я использую этот код, пытаясь прочитать файл из активов. Я попробовал два способа сделать это. Во-первых, при использовании File я получил FileNotFoundException, когда метод AssetManager getAssets() не распознается. Есть ли какое-либо решение здесь?

4b9b3361

Ответ 1

Вот что я делаю в упражнении для буферизованного чтения: расширение/изменение в соответствии с вашими потребностями

BufferedReader reader = null;
try {
    reader = new BufferedReader(
        new InputStreamReader(getAssets().open("filename.txt")));

    // do reading, usually loop until end of file reading  
    String mLine;
    while ((mLine = reader.readLine()) != null) {
       //process line
       ...
    }
} catch (IOException e) {
    //log the exception
} finally {
    if (reader != null) {
         try {
             reader.close();
         } catch (IOException e) {
             //log the exception
         }
    }
}

РЕДАКТИРОВАТЬ: Мой ответ, возможно, бесполезен, если ваш вопрос о том, как сделать это вне деятельности. Если ваш вопрос заключается в том, как просто прочитать файл из ресурса, то ответ выше.

ОБНОВЛЕНИЕ:

Чтобы открыть файл с указанием типа, просто добавьте тип в вызов InputStreamReader следующим образом.

BufferedReader reader = null;
try {
    reader = new BufferedReader(
        new InputStreamReader(getAssets().open("filename.txt"), "UTF-8")); 

    // do reading, usually loop until end of file reading 
    String mLine;
    while ((mLine = reader.readLine()) != null) {
       //process line
       ...
    }
} catch (IOException e) {
    //log the exception
} finally {
    if (reader != null) {
         try {
             reader.close();
         } catch (IOException e) {
             //log the exception
         }
    }
}

РЕДАКТИРОВАТЬ

Как говорит @Stan в комментарии, код, который я даю, не суммирует строки. mLine заменяется каждый проход. Вот почему я написал //process line. Я предполагаю, что файл содержит какие-то данные (например, список контактов), и каждая строка должна обрабатываться отдельно.

В случае, если вы просто хотите загрузить файл без какой-либо обработки, вам нужно будет суммировать mLine на каждом проходе, используя StringBuilder() и добавлять каждый проход.

ДРУГОЕ РЕДАКТИРОВАНИЕ

Согласно комментарию @Vincent я добавил блок finally.

Также обратите внимание, что в Java 7 и выше вы можете использовать try-with-resources для использования AutoCloseable и Closeable недавней Java.

КОНТЕКСТ

В комментарии @LunarWatcher указывает, что getAssets() является class в context. Поэтому, если вы вызываете его вне activity вам нужно обратиться к нему и передать экземпляр контекста в действие.

ContextInstance.getAssets();

Это объясняется в ответе @Maneesh. Так что, если это полезно для вас, проголосуйте за его ответ, потому что тот, кто указал на это.

Ответ 2

getAssets()

работает только в действии в других классах, которые вы должны использовать Context для него.

Создайте конструктор для класса Utils, чтобы передать ссылку на активность (уродливый путь) или контекст приложения в качестве параметра к нему. Используя это, используйте getAsset() в вашем классе Utils.

Ответ 3

Лучше поздно, чем никогда.

У меня были трудности с чтением файлов построчно при некоторых обстоятельствах. Приведенный ниже метод является лучшим, который я нашел, и я рекомендую его.

Использование: String yourData = LoadData("YourDataFile.txt");

Где предполагается, что YourDataFile.txt находится в активах/

 public String LoadData(String inFile) {
        String tContents = "";

    try {
        InputStream stream = getAssets().open(inFile);

        int size = stream.available();
        byte[] buffer = new byte[size];
        stream.read(buffer);
        stream.close();
        tContents = new String(buffer);
    } catch (IOException e) {
        // Handle exceptions here
    }

    return tContents;

 }

Ответ 4

public String ReadFromfile(String fileName, Context context) {
    StringBuilder returnString = new StringBuilder();
    InputStream fIn = null;
    InputStreamReader isr = null;
    BufferedReader input = null;
    try {
        fIn = context.getResources().getAssets()
                .open(fileName, Context.MODE_WORLD_READABLE);
        isr = new InputStreamReader(fIn);
        input = new BufferedReader(isr);
        String line = "";
        while ((line = input.readLine()) != null) {
            returnString.append(line);
        }
    } catch (Exception e) {
        e.getMessage();
    } finally {
        try {
            if (isr != null)
                isr.close();
            if (fIn != null)
                fIn.close();
            if (input != null)
                input.close();
        } catch (Exception e2) {
            e2.getMessage();
        }
    }
    return returnString.toString();
}

Ответ 5

AssetManager assetManager = getAssets();
InputStream inputStream = null;
try {
    inputStream = assetManager.open("helloworld.txt");
}
catch (IOException e){
    Log.e("message: ",e.getMessage());
}

Ответ 6

getAssets() метод будет работать, когда вы вызываете внутри класса Activity.

Если вы вызываете этот метод в классе non-Activity, вам необходимо вызвать этот метод из контекста, который передается из класса Activity. Итак, ниже строка, вы можете получить доступ к методу.

ContextInstance.getAssets();

ContextInstance может быть передан как класс Activity.

Ответ 7

Чтение и запись файлов всегда были многословны и подвержены ошибкам. Избегайте этих ответов и просто используйте Okio вместо этого:

public void readLines(File file) throws IOException {
  try (BufferedSource source = Okio.buffer(Okio.source(file))) {
    for (String line; (line = source.readUtf8Line()) != null; ) {
      if (line.contains("square")) {
        System.out.println(line);
      }
    }
  }
}

Ответ 8

Вот способ чтения файла в активах:

/**
 * Reads the text of an asset. Should not be run on the UI thread.
 * 
 * @param mgr
 *            The {@link AssetManager} obtained via {@link Context#getAssets()}
 * @param path
 *            The path to the asset.
 * @return The plain text of the asset
 */
public static String readAsset(AssetManager mgr, String path) {
    String contents = "";
    InputStream is = null;
    BufferedReader reader = null;
    try {
        is = mgr.open(path);
        reader = new BufferedReader(new InputStreamReader(is));
        contents = reader.readLine();
        String line = null;
        while ((line = reader.readLine()) != null) {
            contents += '\n' + line;
        }
    } catch (final Exception e) {
        e.printStackTrace();
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ignored) {
            }
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ignored) {
            }
        }
    }
    return contents;
}

Ответ 9

В MainActivity.java

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView tvView = (TextView) findViewById(R.id.tvView);

        AssetsReader assetsReader = new AssetsReader(this);
        if(assetsReader.getTxtFile(your_file_title)) != null)
        {
            tvView.setText(assetsReader.getTxtFile(your_file_title)));
        }
    }

Кроме того, вы можете создать отдельный класс, который выполняет всю работу

public class AssetsReader implements Readable{

    private static final String TAG = "AssetsReader";


    private AssetManager mAssetManager;
    private Activity mActivity;

    public AssetsReader(Activity activity) {
        this.mActivity = activity;
        mAssetManager = mActivity.getAssets();
    }

    @Override
    public String getTxtFile(String fileName)
    {
        BufferedReader reader = null;
        InputStream inputStream = null;
        StringBuilder builder = new StringBuilder();

        try{
            inputStream = mAssetManager.open(fileName);
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;

            while((line = reader.readLine()) != null)
            {
                Log.i(TAG, line);
                builder.append(line);
                builder.append("\n");
            }
        } catch (IOException ioe){
            ioe.printStackTrace();
        } finally {

            if(inputStream != null)
            {
                try {
                    inputStream.close();
                } catch (IOException ioe){
                    ioe.printStackTrace();
                }
            }

            if(reader != null)
            {
                try {
                    reader.close();
                } catch (IOException ioe)
                {
                    ioe.printStackTrace();
                }
            }
        }
        Log.i(TAG, "builder.toString(): " + builder.toString());
        return builder.toString();
    }
}

По-моему, лучше создать интерфейс, но это не обязательно

public interface Readable {
    /**
     * Reads txt file from assets
     * @param fileName
     * @return string
     */
    String getTxtFile(String fileName);
}

Ответ 10

Вы можете загрузить содержимое из файла. Рассмотрим, что файл присутствует в папке с ресурсами.

public static InputStream loadInputStreamFromAssetFile(Context context, String fileName){
    AssetManager am = context.getAssets();
    try {
        InputStream is = am.open(fileName);
        return is;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

public static String loadContentFromFile(Context context, String path){
    String content = null;
    try {
        InputStream is = loadInputStreamFromAssetFile(context, path);
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        content = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return content;
}

Теперь вы можете получить контент, вызвав функцию, следуя

String json= FileUtil.loadContentFromFile(context, "data.json");

Учитывая, что data.json хранится в приложении\app\src\main\assets\data.json

Ответ 11

Однострочное решение для котлина:

fun readFileText(fileName: String): String {
    return assets.open(fileName).bufferedReader().use { it.readText() }
}

Ответ 12

Если вы используете другой класс, отличный от Activity, вы можете сделать, например,

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader( YourApplication.getInstance().getAssets().open("text.txt"), "UTF-8"));

Ответ 13

Используя Kotlin, вы можете сделать следующее, чтобы прочитать файл из ресурсов в Android:

try {
    val inputStream:InputStream = assets.open("helloworld.txt")
    val inputString = inputStream.bufferedReader().use{it.readText()}
    Log.d(TAG,inputString)
} catch (e:Exception){
    Log.d(TAG, e.toString())
}

Ответ 14

cityfile.txt

   public void getCityStateFromLocal() {
        AssetManager am = getAssets();
        InputStream inputStream = null;
        try {
            inputStream = am.open("city_state.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }
        ObjectMapper mapper = new ObjectMapper();
        Map<String, String[]> map = new HashMap<String, String[]>();
        try {
            map = mapper.readValue(getStringFromInputStream(inputStream), new TypeReference<Map<String, String[]>>() {
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        ConstantValues.arrayListStateName.clear();
        ConstantValues.arrayListCityByState.clear();
        if (map.size() > 0)
        {
            for (Map.Entry<String, String[]> e : map.entrySet()) {
                CityByState cityByState = new CityByState();
                String key = e.getKey();
                String[] value = e.getValue();
                ArrayList<String> s = new ArrayList<String>(Arrays.asList(value));
                ConstantValues.arrayListStateName.add(key);
                s.add(0,"Select City");
                cityByState.addValue(s);
                ConstantValues.arrayListCityByState.add(cityByState);
            }
        }
        ConstantValues.arrayListStateName.add(0,"Select States");
    }
 // Convert InputStream to String
    public String getStringFromInputStream(InputStream is) {
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            br = new BufferedReader(new InputStreamReader(is));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return sb + "";

    }

Ответ 15

Вот способ получить InputStream для файла в папке assets без Context, Activity, Fragment или Application. Как вы получаете данные из этого InputStream, зависит от вас. Есть много предложений для этого в других ответах здесь.

Котлин

val is = ClassLoader::class.java.classLoader.getResourceAsStream("assets/your_file.ext")

Джава

InputStream is = ClassLoader.class.getClassLoader().getResourceAsStream("assets/your_file.ext");

Все ставки отключены, если в ClassLoader находится пользовательский ClassLoader.

Ответ 16

@HpTerm ответить на версию Kotlin:

private fun getDataFromAssets(): String? {

    var bufferedReader: BufferedReader? = null
    var data: String? = null

    try {
        bufferedReader = BufferedReader(
            InputStreamReader(
                activity?.assets?.open("Your_FILE.html"),     
                "UTF-8"
            )
        )                  //use assets? directly if in activity

       var mLine:String = bufferedReader?.readLine()
        while (mLine != null) {
            data+= mLine
            mLine=bufferedReader.readLine()
        }

    } catch (e: Exception) {
        e.printStackTrace()
    } finally {
        try {
            bufferedReader?.close()
        } catch (e: Exception) {
           e.printStackTrace()
        }
    }
    return data
}