我设置了 3 个 TextView ,每个 View 最多包含 9 个字符。用户可以编辑这些 TextView 并将它们保存到文件中。我首先将字符串数组转换为字符串。
StrLabels[0]=label1.getText().toString();
StrLabels[1]=label2.getText().toString();
StrLabels[2]=label3.getText().toString();
StrFile=(StrLabels[0] + StrLabels[1] + StrLabels[2]);
writeToFile(StrFile);
StrFile 可以很好地保存 3 个字符串,但我还需要反转该过程并读取文件。有没有办法将每个 StrLabels[] 与 StrFile 分开。
谢谢 Gianmarco,这是在您的帮助下的最终代码。我反转了 toBeAdded,因此它添加到字符串的末尾而不是前面。
String totalString = ""; // initialization of the total string
String piece = StrLabels[0];
String toBeAdded = "";
if(piece.length() < 9){
int length = piece.length();
toBeAdded = piece;
while(length < 9){
toBeAdded =toBeAdded +"";
length++;
}
} else if(piece.length() > 9){
throw new IllegalArgumentException ("Error, string longer than 9");
} else {
toBeAdded = piece;
}
totalString = totalString + toBeAdded;
最佳答案
一个基本的解决方案是使用分隔符,但这意味着要处理分隔符位于字符串中的情况,这意味着要确保其正常工作会遇到很多麻烦。更简单的解决方案是依赖现有方法。
JSON
只需创建一个 JSONArray
,将字符串放入其中,然后在 JSONArray
上调用 toString
。
通过解析 JSONArray
中读取的字符串来进行反转
创建 JSONArray 的简单方法是:
JSONArray array = new JSONArray(Arrays.asList(StrLabels));
// The output String is simply
String StrFile = array.toString();
数据输出流
写入文件时,您使用FileOutputStream
。您可以在其之上打开一个 DataOutputStream
,并使用 writeUTF
将字符串写入文件。
通过在文件上打开 DataInputStream
并调用 readUTF
来反转
关于java - 字符串数组到带有格式的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18897286/