将2D数组写入字符串,然后写入.txt文件-Java
我有一个方法调用第二个方法,第二个方法将:将2D数组写入字符串,然后写入.txt文件-Java,java,string,file,multidimensional-array,Java,String,File,Multidimensional Array,我有一个方法调用第二个方法,第二个方法将: 创建任何缺少的目录 创建一个文件 将2D字符串[]解码为字符串(不工作) 写内容 将解码的字符串写入带有头的文件(不工作) 第一种方法 public static boolean store(Exception exception, String[][] flags){ return storePrivate(exception, location, flags); } public static void main(String[] a
- 创建任何缺少的目录
- 创建一个文件
- 将2D字符串[]解码为字符串(不工作)
- 写内容
- 将解码的字符串写入带有头的文件(不工作)
public static boolean store(Exception exception, String[][] flags){
return storePrivate(exception, location, flags);
}
public static void main(String[] args) {
try {
test();
} catch (Exception e) {
// TODO Auto-generated catch block
ExceptionAPI.store(e, new String[][]{{"flag1", "Should be part of flag1"}, {"flag2", "this should be flag 2 contence"}});
}
}
public static void test() throws IOException{
throw new IOException();
}
第二种方法(不是所有代码,只是相关代码)
调用第一个方法
public static boolean store(Exception exception, String[][] flags){
return storePrivate(exception, location, flags);
}
public static void main(String[] args) {
try {
test();
} catch (Exception e) {
// TODO Auto-generated catch block
ExceptionAPI.store(e, new String[][]{{"flag1", "Should be part of flag1"}, {"flag2", "this should be flag 2 contence"}});
}
}
public static void test() throws IOException{
throw new IOException();
}
我不明白为什么这行不通。我认为这与第二种方法有关,尤其是
if(flag != ""){
writer.write("Flags by Developer: ");
writer.write(flag);
}
如果有人能帮助我,谢谢你
Curlip如果您只想将字符串数组转换为单个字符串,请尝试以下操作:
String[] stringTwoD = //... I think this is a 1D array, and Sting[][] is a 2D, anyway
String stringOneD = "";
for (String s : stringTwoD)
stringOneD += s;//add the string with the format you want
顺便说一句,您的循环条件似乎错误,因此您可以将其更改为:
for(int i = 0; i < flags.length; i++){
flag += flags[i][0] + ": " + flags[i][1] + "\n";
}
for(int i=0;i
正是。。。OP写入。。。i>=flags.length;i++
你最好使用StringBuilder
@ambigram\u maker>我只是想通知他/她他应该做的更改。我也将添加这种方法。OP
被普遍接受,而不是him/her
。不过,OP的数组是二维的(String[][]
)。他的方法基本上是好的,除了@ambigram\u-maker指出的i>=flags.length
。方法中的异常
有什么用?正如@ambigram\u-maker在对第一个答案的评论中指出的,您的循环条件i>=flags.length
是错误的,应该是i
。您将i
初始化为0
,该值不大于或等于标志。当长度包含任何元素时(length
将为1
)。@ambigram\u maker是我遗漏的代码的一部分