我正在将 JSON 文件保存到 Android 上的私有目录中。问题是当我阅读文件时,文本最后会填充奇怪的字符,我不确定为什么会发生这种情况。
日志:
E/WRITTEN(25254): {"sex":"MALE","activity_factor":1.2,"weight":0,"height":180.0,"weight_loss_goal":0,"age":30}
E/StartActivity(25254):重新启动 07-03
E/READ(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 ();
}
}