source

자산에서 파일 읽기

ittop 2023. 9. 14. 23:35
반응형

자산에서 파일 읽기

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()메서드를 인식할 수 없습니다.여기에 해결책이 있습니까?

다음은 버퍼링된 읽기 작업에서 귀하의 요구에 맞게 확장/수정하기 위한 작업입니다.

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최근 자바의 특징들.

맥락

@LunarWatcher는 논평에서 다음을 지적합니다.getAssets()class인에context. 그래서, 만약 당신이 그것을 밖에서 부른다면,activity참조하고 컨텍스트 인스턴스를 작업에 전달해야 합니다.

ContextInstance.getAssets();

이것은 @Manesh의 대답에서 설명됩니다.그 점을 지적한 사람이 바로 그이기 때문에 이것이 당신에게 도움이 된다면 그의 대답을 지지해 줄 것입니다.

getAssets()

사용해야 하는 다른 클래스의 액티비티에서만 작동합니다.Context그 때문에

Utils 클래스의 생성자가 활동(못생긴 방식) 또는 응용프로그램 컨텍스트를 매개변수로 통과시킵니다.Utils 클래스에서 getAsset()을 사용합니다.

늦더라도 안 하느니보다는 낫다.

어떤 상황에서는 파일을 한 줄씩 읽는 데 어려움을 겪었습니다.제가 찾은 방법 중에 아래 방법이 가장 좋으며, 추천합니다.

용도:String yourData = LoadData("YourDataFile.txt");

여기에 데이터 파일을 입력합니다.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;

 }
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();
}

코틀린에 대한 한 줄 솔루션:

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

또한 확장 기능으로 사용할 수 있습니다.어디에

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

아무 컨텍스트에서나 클래스를 호출하기만 하면 됩니다.

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

getAssets()메서드는 Activity 클래스 내에서 호출할 때 작동합니다.

비활동 클래스에서 이 메서드를 호출하는 경우 활동 클래스에서 전달된 컨텍스트에서 이 메서드를 호출해야 합니다.아래는 당신이 접근할 수 있는 방법입니다.

ContextInstance.getAssets();

ContextInstance액티비티 클래스의 이것으로 통과될 수 있습니다.

파일을 읽고 쓰는 것은 항상 장황하고 오류가 발생하기 쉽습니다.다음과 같은 답변은 피하고 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);
      }
    }
  }
}

자산의 파일을 읽는 방법은 다음과 같습니다.

/**
 * 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;
}

파일에서 내용을 로드할 수 있습니다.파일이 자산 폴더에 있다고 가정합니다.

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이 Application\app\src\main\assets\data.json에 저장되어 있음을 고려하면

주 활동.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);
}

여기에 한가지 방법이 있습니다.InputStream에n의 assets가는더더a는tContext,Activity,Fragment아니면Application. 어떻게 그걸 통해 데이터를 얻는지에 대해InputStream◦ ◦ 에 있는이 많이 .여기에 있는 다른 답변들에는 그것에 대한 제안들이 많이 있습니다.

코틀린

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

자바

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

사용자 지정인 경우 모든 베팅이 꺼집니다.ClassLoader재생 중입니다.

예외 증명

It maybe too late but for the sake of others who look for the peachy answers.

loadAssetFile()method는 자산의 일반 텍스트를 반환하거나 잘못된 경우 defaultValue 인수를 반환합니다.

public static String loadAssetFile(Context context, String fileName, String defaultValue) {
    String result=defaultValue;
    InputStreamReader inputStream=null;
    BufferedReader bufferedReader=null;
    try {
        inputStream = new InputStreamReader(context.getAssets().open(fileName));
        bufferedReader = new BufferedReader(inputStream);
        StringBuilder out= new StringBuilder();
        String line = bufferedReader.readLine();
        while (line != null) {
            out.append(line);
            line = bufferedReader.readLine();
        }
        result=out.toString();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            Objects.requireNonNull(inputStream).close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            Objects.requireNonNull(bufferedReader).close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return result;
}

액티비티가 아닌 다른 클래스를 사용하는 경우, 좋아요를 할 수 있습니다.

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

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())
}

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 + "";

    }

스캐너 클래스는 이를 단순화할 수 있습니다.

        StringBuilder sb=new StringBuilder();
        Scanner scanner=null;
        try {
            scanner=new Scanner(getAssets().open("text.txt"));
            while(scanner.hasNextLine()){
                sb.append(scanner.nextLine());
                sb.append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(scanner!=null){try{scanner.close();}catch (Exception e){}}
        }
        mTextView.setText(sb.toString());

@HpTerm 답변 Kotlin 버전:

private fun getDataFromAssets(activity: Activity): String {

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

    try {
        bufferedReader = BufferedReader(
            InputStreamReader(
                activity?.assets?.open("Your_FILE.html"),
                "UTF-8"
            )
        )                  //use assets? directly if inside the 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
}

언급URL : https://stackoverflow.com/questions/9544737/read-file-from-assets

반응형