我正在将JSON文件保存到Android上的私人目录中。问题是,当我读取文件时,文本最后填充了奇怪的字符,我不知道为什么会发生这种情况。
日志:
E /书面(25254): { “性别”: “男”, “activity_factor”:1.2, “重量”:0, “高度”:180.0, “weight_loss_goal”:0, “年龄”:30}
E / StartActivity(25254):RELAUNCH 07-03
E / READ(25254): { “性别”: “男”, “activity_factor”:1.2, “重量”:0, “高度”:180.0, “weight_loss_goal”:0, “年龄”:30} ??????????? ?????????????????????????????????????????????????? ????????????????????????????????????????????????
FileWrite i / o code:
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 ();
}
}
答案 0 :(得分:2)
您假设整个1024字节缓冲区已被读取填充,只有在文件至少那么长时才会出现这种情况。显然它不是,所以你在读取停止的地方显示了很多未初始化的内存。
您使用的read()版本的返回值是读取的字节数。将其保存在变量中,而不是仅检查失败,然后只尝试使用缓冲区的那么多字节。
答案 1 :(得分:0)
在阅读文件时使用新的InputStreamReader(是,“windows-1252”)。这应该能够解决这个问题。