首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >找不到Typeface.createFromFile文件?

找不到Typeface.createFromFile文件?
EN

Stack Overflow用户
提问于 2017-08-16 13:26:19
回答 3查看 3K关注 0票数 1

在此之前,我发布了一个问题,并获得了存储在Data / too.But /com.customfonts/Robotoo.ttf中的解决方案数据,但其搜索文件的路径错误,并抛出了Font not found /data/user/0/com.customfonts/files/Robottoo.ttf

Downloading file from url error " java.io.FileNotFoundException: /Users/Documents (No such file or directory)",但是我面对的文件没有找到exception.Here,这是我的代码,我已经试过了。

代码语言:javascript
复制
   //  Storing file 
    private class DownloadingTask  extends AsyncTask<Void,Void,Void>{
    @Override
    protected Void doInBackground(Void... voids) {
        try {
            URL url = new URL(fonturl);
            HttpURLConnection c = (HttpURLConnection) url.openConnection();
            c.setRequestMethod("GET");
            c.connect();
            FileOutputStream fos = new FileOutputStream(new File(getFilesDir(),"Robotto.ttf"));
            Log.i("Download","complete");
            Log.i("File",getFilesDir().getAbsolutePath());
        ( I/File: /data/user/0/com.customfonts/files)//files stores under
            Log.i("FOS",""+fos.toString());

            InputStream is = c.getInputStream();
            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len1);
            }
            fos.close();
            is.close();
        }
        catch (Exception e) {
            e.printStackTrace();
            outputFile = null;
            Log.e("Error", "Download Error Exception " + e.getMessage());
        }

        return null;
    }
}

 btnGETDATA.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
         String filename="Robottoo.ttf";
         getTypeface(filename);
         }
    });
   private Typeface getTypeface(String filename)
   {
     Typeface font;
        try
        {
            font = Typeface.createFromFile(getFilesDir().getAbsolutePath() +"/"+filename);
            Log.i("FOnt found",""+font);
           (java.lang.RuntimeException: Font not found /data/user/0/com.customfonts/files/Robotoo.ttf)
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
        return  font;
   }

Font : /data/user/0/com.customfonts/files/Robottoo.ttf未找到java.lang.RuntimeException

EN

回答 3

Stack Overflow用户

发布于 2017-08-16 15:28:18

尝试使用getFilesDir()getExternalFilesDir()方法

getExternalFilesDir方法给出了你的应用程序私人文件夹目录的路径,你可以在这里存储你的ttf文件以获取更多信息,请查看this

代码语言:javascript
复制
   File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES),filename);
   if (!file.mkdirs()) {
     Log.e(LOG_TAG, "Directory not created");
   }
   font = Typeface.createFromFile(file.getPath());

另一种方式-尝试此ContextWrapper.getFilesDir() check

票数 0
EN

Stack Overflow用户

发布于 2017-08-16 17:28:13

你可以试试这种方式,

1.检查目录是否存在如果不存在,则创建目录

代码语言:javascript
复制
    File rootDirectory;
    PackageManager m = getPackageManager();
    String s = getPackageName();
    PackageInfo p = null;
    try {
        p = m.getPackageInfo(s, 0);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    s = p.applicationInfo.dataDir;

    rootDirectory = new File(s + "/files");

    if (!rootDirectory.exists()) {
        rootDirectory.mkdir();
    }

    String FileName = "Robotto.ttf";
    String finalUrl = rootDirectory.getAbsolutePath() + "/" + FileName;

2.代码中的一些更改

代码语言:javascript
复制
 private class DownloadingTask  extends AsyncTask<Void,Void,Void> {
            @Override
            protected Void doInBackground(Void... voids) {
                try {
                    File rootDirectory = null;
                    URL url = new URL(fonturl);
                    HttpURLConnection c = (HttpURLConnection) url.openConnection();
                    c.setRequestMethod("GET");
                    c.connect();
                    FileOutputStream fos = new FileOutputStream(finalUrl);
                  //  Log.i("Download","complete");
                   // Log.i("File",getFilesDir().getAbsolutePath());
                  //  ( I/File: /data/user/0/com.customfonts/files)//files stores under
                   // Log.i("FOS",""+fos.toString());

                    InputStream is = c.getInputStream();
                    byte[] buffer = new byte[1024];
                    int len1 = 0;
                    while ((len1 = is.read(buffer)) != -1) {
                        fos.write(buffer, 0, len1);
                    }
                    fos.close();
                    is.close();
                }
                catch (Exception e) {
                    e.printStackTrace();
                    outputFile = null;
                    Log.e("Error", "Download Error Exception " + e.getMessage());
                }

                return null;
            }
        }

        btnGETDATA.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               // String filename="Robottoo.ttf";
                getTypeface(finalUrl);
            }
        });
        private Typeface getTypeface(String finalUrl)
        {
            Typeface font;
            try
            {
                font = Typeface.createFromFile(finalUrl);
              //  Log.i("FOnt found",""+font);
              //  (java.lang.RuntimeException: Font not found /data/user/0/com.customfonts/files/Robotoo.ttf)
            }
            catch (Exception e)
            {
                e.printStackTrace();
                return null;
            }
            return  font;
        }

我希望这能对你有所帮助。

更新1:

检查一次你的文件名“Robotto.ttf” this is different name。

代码语言:javascript
复制
btnGETDATA.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
         String filename="Robottoo.ttf";
         getTypeface(filename);
         }
    });

你应该使用

代码语言:javascript
复制
btnGETDATA.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
         String filename="Robotto.ttf";
         getTypeface(filename);
         }
    });

更新2:

检查您的应用程序是否具有"WRITE_EXTERNAL_STORAGE"权限。

代码语言:javascript
复制
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

有关更多详细信息,请访问抛出的Write a file in external storage in Android

更新3:(只需复制并粘贴代码即可)

1. WriteSDCard.java

代码语言:javascript
复制
    import android.Manifest;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class WriteSDCard extends AppCompatActivity {

    String finalUrl;
    private TextView tv;
    private String fonturl= "http://github.com/google/fonts/blob/master/apache/roboto/Roboto-Regular.ttf?raw=true";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if(isStoragePermissionGranted()){
            checkExternalMedia();
            writeToFile();

            new DownloadingTask().execute();
        }


    }

    private void checkExternalMedia(){
        boolean mExternalStorageAvailable = false;
        boolean mExternalStorageWriteable = false;
        String state = Environment.getExternalStorageState();

        if (Environment.MEDIA_MOUNTED.equals(state)) {
            // Can read and write the media
            mExternalStorageAvailable = mExternalStorageWriteable = true;
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            // Can only read the media
            mExternalStorageAvailable = true;
            mExternalStorageWriteable = false;
        } else {
            // Can't read or write
            mExternalStorageAvailable = mExternalStorageWriteable = false;
        }
        tv.append("\n\nExternal Media: readable="
                +mExternalStorageAvailable+" writable="+mExternalStorageWriteable);
    }

    private void writeToFile(){

        File rootDirectory;
        PackageManager m = getPackageManager();
        String s = getPackageName();
        PackageInfo p = null;
        try {
            p = m.getPackageInfo(s, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        s = p.applicationInfo.dataDir;

        rootDirectory = new File(s + "/files");

        if (!rootDirectory.exists()) {
            rootDirectory.mkdir();
        }

        String FileName = "Roboto-Regular.ttf";
        finalUrl= rootDirectory.getAbsolutePath() + "/" + FileName;
    }

    private class DownloadingTask  extends AsyncTask<Void,Void,Void> {
        @Override
        protected Void doInBackground(Void... voids) {
            try {
                URL url = new URL(fonturl);
                HttpURLConnection c = (HttpURLConnection)url.openConnection();
                c.setRequestMethod("GET");
                c.connect();
                FileOutputStream fos = new FileOutputStream(finalUrl); // File you want to save to, It creates Roboto-Regular.ttf in your Internal Storage you got from "getFilesDir() method
                Log.i("Download","complete");
                InputStream is = c.getInputStream();
                byte[] buffer = new byte[1024];
                int len1 = 0;
                while ((len1 = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len1);
                }
                fos.close();
                is.close();
            }
            catch (Exception e) {
                e.printStackTrace();
               // outputFile = null;
                Log.e("Error", "Download Error Exception " + e.getMessage());
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
          //  super.onPostExecute(aVoid);

            File file = new File(finalUrl);
            if(file.exists()) {
                //something,
                Toast.makeText(WriteSDCard.this,"File exists",Toast.LENGTH_SHORT).show();
                /**
                 *
                 */
                getTypeface();

            }
            else{
               //something
                Toast.makeText(WriteSDCard.this,"File Not exists",Toast.LENGTH_SHORT).show();

            }
        }
    }

    private Typeface getTypeface()
    {
        Typeface font;
        try
        {
            font = Typeface.createFromFile(finalUrl);
            Log.i("Font found",""+font);
         }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
        return  font;
    }

    public  boolean isStoragePermissionGranted() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    == PackageManager.PERMISSION_GRANTED) {
               // Log.v(TAG,"Permission is granted");
                return true;
            } else {

               // Log.v(TAG,"Permission is revoked");
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                return false;
            }
        }
        else { //permission is automatically granted on sdk<23 upon installation
           // Log.v(TAG,"Permission is granted");
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
           // Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
            //resume tasks needing this permission
        }
    }

}

2.清单文件

代码语言:javascript
复制
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="example.download_fontform_url">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".WriteSDCard">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
票数 0
EN

Stack Overflow用户

发布于 2017-08-16 13:53:24

在应用程序级别的层次结构中创建assets文件夹,并将.ttf字体文件粘贴到其中。

并使用此代码来应用字体

代码语言:javascript
复制
Typeface face = Typeface.createFromAsset(getAssets(), "font.ttf");
textview.setTypeface(face);
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45705679

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档