【发布时间】:2013-07-03 10:58:12
【问题描述】:
我正在将 JSON 文件保存到 Android 上的私有目录中。问题是当我阅读文件时,文本最后会被奇怪的字符填充,我不确定为什么会这样。
日志:
电子/书面(25254): {"sex":"MALE","activity_factor":1.2,"weight":0,"height":180.0,"weight_loss_goal":0,"age":30}
E/StartActivity(25254):重新启动 07-03
电子/阅读(25254): {"sex":"MALE","activity_factor":1.2,"weight":0,"height":180.0,"weight_loss_goal":0,"age":30}??????????? ??????????????????????????????????????????????????? ?????????????????????????????????..(这样一直不停)
FileWrite i/o 代码:
public class FileUtil
{
public static void writeToFile ( Context context, String filename, String text, int mode ) throws IOException
{
FileOutputStream fos = null;
try
{
fos = context.openFileOutput ( filename, mode );
fos.write ( text.getBytes () );
Log.e("WRITTEN",text);
}
catch ( FileNotFoundException e )
{
throw e;
}
catch ( IOException e )
{
throw e;
}
finally
{
if ( fos != null )
{
try
{
fos.close ();
}
catch ( IOException e )
{
}
}
}
}
public static String readFromFile ( Context context, String fileName ) throws IOException
{
FileInputStream fis = null;
StringBuilder content = new StringBuilder ( "" );
try
{
byte [] buffer = new byte [1024];
fis = context.openFileInput ( fileName );
while ( fis.read ( buffer ) != -1 )
{
content.append ( new String ( buffer ) );
}
}
catch ( FileNotFoundException e )
{
throw e;
}
catch ( IOException e )
{
throw e;
}
finally
{
if ( fis != null )
{
try
{
fis.close ();
}
catch ( IOException e )
{
// TODO Auto-generated catch block
e.printStackTrace ();
}
}
}
Log.e("READ",content.toString ());
return content.toString ();
}
}
【问题讨论】:
-
那么在这种情况下什么是“模式”?该文件是否事先存在?顺便说一句,在不指定编码的情况下使用 String.getBytes 是个坏主意。
-
尝试使用
text.getBytes("UTF-8")和new String(buffer, "UTF-8")。 -
我不知道,我在关注 Android 开发者页面上的示例。尽管如此,它仍然不起作用。