0

我正在将 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 ();
    }
}
4

2 回答 2

2

您假设整个 1024 字节缓冲区已被读取填充,只有当文件至少有那么长时才会出现这种情况。显然不是,因此您在读取停止的位置之外显示了大量未初始化的内存。

您正在使用的 read() 版本的返回值是读取的字节数。将其保存在一个变量中,而不是只检查失败,然后只尝试使用缓冲区的那么多字节。

于 2013-07-03T11:14:56.963 回答
0

读取文件时使用 new InputStreamReader(is, "windows-1252")。那应该可以解决问题。

于 2013-07-03T11:06:06.520 回答