我在assets文件夹中使用了不同的文本文件(arabic.txt ,english.txt),我想改变设备语言的文件库。
可以在valuestring文件中设置文件名吗?
public static class TipsSource{
// if language arabic select file arabic.txt
// if language english select file english.txt
public static String English="english.txt";
}
字符串文件
<string name="LangFile">"english.txt"</string>
我试过
public static String English=getResources().getString(R.string.LangFile);
和
public static String English= getString(R.string.LangFile);
和
public static String English= R.string.LangFile;
更新 "已解决"
我创建了assetsenfile.txtassetsarfile.txt。
TxtFile = file.txt
reader = new BufferedReader(
new InputStreamReader(context.getAssets().open((context.getString(R.string.tips) + TxtFile))));
文件串
<string name="langdir">en/</string>
可能是引号是多余的。
<string name="LangFile">english.txt</string>
你可以试试这个。
不能,因为静态不能得到context,getResources()必须需要context
getClass()
方法不能用在静态方法中,所以我做了这样的方法。
import java.io.File;
import java.net.URL;
public class ResourceTest {
public static String EnglishTextFile = "english.txt";
public static String ArabicTextFile = "arabic.txt";
public static void main(String[] args) {
String textLanguage = "";
// case 1 : load value from arguments of main method.
textLanguage = args[0];
// case 2: just wrote what you want.
textLanguage = EnglishTextFile;
ResourceTest resourceTest = new ResourceTest();
resourceTest.readTextFile(textLanguage);
}
public File readTextFile(String fileName) throws IllegalArgumentException {
ClassLoader classLoader = getClass().getClassLoader();
URL resource = classLoader.getResource(fileName);
if (resource != null) {
return new File(resource.getFile());
} else {
throw new IllegalArgumentException("Not found file. File name is '" + fileName + "'");
}
}
}
为了达到本地化的目的,我会使用 /res
文件夹,而不是 /assets
.你可以把这些文本文件放在 /res/raw
为您的默认语言(阿拉伯语)和 /res/raw-en
用于翻译成英文。(注意必须使用相同的文件名)
/res/raw/file.txt
/res/raw-en/file.text
这样一来,你就不用管语言之间的资源切换了。这将是Android OS的事情。
InputStream inputStream = resources.openRawResource(R.raw.file);
我的应用程序重绘文件夹也不能用了
所以我喜欢这个assetsarfile.txt。
TxtFile = file.txt
reader = new BufferedReader(
new InputStreamReader(context.getAssets().open((context.getString(R.string.langdir) + TxtFile))));
文件串
<string name="langdir">en/</string>