【发布时间】:2012-12-22 13:23:18
【问题描述】:
我正在编写 .json 文件,我想读取该文件, 但问题是,当我尝试将整个文件作为字符串读取时,它会在每个字符之前和之后添加空格,并且只是因为额外的字符而无法读取 json。
Json 格式为
[{"description1":"The ThinkerA bronze sculpture by Auguste Rodin. It depicts a man in sober\nmeditation battling with a powerful internal struggle.","description2":"Steve JobsFounder of Apple, he is widely recognized as a charismatic pioneer of\nthe personal computer revolution.","description3":"Justin BieberBorn in 1994, the latest sensation in music industry with numerous\nawards in recent years."}]
但它给出了奇怪的响应,例如: [ { " d e s c r i p t i o n 1 " : " T h e .....
修剪多余的空间我提到了这个,但仍然没有工作: Java how to replace 2 or more spaces with single space in string and delete leading spaces only
我正在使用此代码
File folderPath = Environment.getExternalStorageDirectory();
File mypath=new File(folderPath, "description.json");
StringBuffer fileData = new StringBuffer(1000);
BufferedReader reader = null;
reader = new BufferedReader(new FileReader(mypath));
char[] buf = new char[1024];
int numRead=0;
while((numRead=reader.read(buf)) != -1)
{
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
buf = new char[1024];
}
String response = fileData.toString();
“响应”字符串包含奇怪的响应
谁能帮帮我?
用于写入文件,我使用:
FileOutputStream fos = new FileOutputStream(mypath);
DataOutputStream dos = new DataOutputStream(fos);
dos.writeChars(response);
【问题讨论】:
-
BufferedReader有readLine方法。尝试使用它。 -
你能贴出你用来写文件的代码吗?听起来您可能正在以 16 位格式编写字符。
-
尝试打开文件,查看内容是否包含空格或不可见字符。还可以尝试记录以查看每次迭代在 numRead 和 readData 中返回的内容。这是为了缩小范围并确保问题出在阅读而不是写作。
-
@RobGThai ,我正在使用 writeChars 编写,这会导致在每个字符之前写入空格,现在我使用 writeUTF 并解决了问题。感谢大家分享他们的意见。
标签: android json string file-io