在此之前,我发布了一个问题,并获得了存储在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,这是我的代码,我已经试过了。
// 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
发布于 2017-08-16 15:28:18
尝试使用getFilesDir()的getExternalFilesDir()方法
getExternalFilesDir方法给出了你的应用程序私人文件夹目录的路径,你可以在这里存储你的ttf文件以获取更多信息,请查看this。
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
发布于 2017-08-16 17:28:13
你可以试试这种方式,
1.检查目录是否存在如果不存在,则创建目录
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.代码中的一些更改
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。
btnGETDATA.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String filename="Robottoo.ttf";
getTypeface(filename);
}
});你应该使用
btnGETDATA.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String filename="Robotto.ttf";
getTypeface(filename);
}
});更新2:
检查您的应用程序是否具有"WRITE_EXTERNAL_STORAGE"权限。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>有关更多详细信息,请访问抛出的Write a file in external storage in Android
更新3:(只需复制并粘贴代码即可)
1. WriteSDCard.java
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.清单文件
<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>发布于 2017-08-16 13:53:24
在应用程序级别的层次结构中创建assets文件夹,并将.ttf字体文件粘贴到其中。
并使用此代码来应用字体
Typeface face = Typeface.createFromAsset(getAssets(), "font.ttf");
textview.setTypeface(face);https://stackoverflow.com/questions/45705679
复制相似问题