【问题标题】:Writing a 2D Array to a string, then to a .txt file - Java将二维数组写入字符串,然后写入 .txt 文件 - Java
【发布时间】:2014-06-02 16:06:10
【问题描述】:

我有一个调用第二种方法的方法,第二种方法将:

  • 创建所有缺失的目录
  • 创建文件
  • 将二维字符串 [] 解码为字符串(不工作)
  • 写内容
  • 将解码后的字符串写入带有标题的文件(不工作)

第一种方法

public static boolean store(Exception exception, String[][] flags){
    return storePrivate(exception, location, flags);
}

第二种方法(并非所有代码都只是相关代码)

private static boolean storePrivate(Exception exception, String dir, String[][] flags){
    String flag = "";

    for(int i = 0; i >= flags.length; i++){
        flag = flag + "" +  flags[i][0] + ": " + flags[i][1] + "\n";
    }
    try {
        File directory = new File(dir);
        File file = new File(dir + id + ".txt");
        if (!directory.exists()) {
            directory.mkdirs(); 
        }
        file.createNewFile();
        FileWriter filewriter = new FileWriter(file.getAbsoluteFile());
        BufferedWriter writer = new BufferedWriter(filewriter);


        if(flag != ""){
            writer.write("Flags by Developer: ");
            writer.write(flag);
        }   
        writer.flush();
        writer.close();
        return true;
    } catch (IOException e) {
        return false;
    }
}

调用第一个方法

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);
}  

如果有人可以帮助我,谢谢。

卷发

【问题讨论】:

  • 方法中Exception有什么用?
  • 正如@ambigram_maker 在对第一个答案的评论中指出的那样,您的循环条件i >= flags.length 是错误的,应该改为i < flags.length。你将i初始化为0,当它包含任何元素时,它不大于或等于flags.lengthlength将是1)。
  • @ambigram_maker 部分代码我遗漏了

标签: java string file multidimensional-array


【解决方案1】:

如果您只想将字符串数组转换为单个字符串,请尝试以下操作:

    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";
}

【讨论】:

  • 完全正确... OP 写道 ... i &gt;= flags.length; i++)...
  • 你最好使用StringBuilder
  • @ambigram_maker> 我只是想通知他/她他应该做出的改变。我也会添加这种方法。
  • OP 被普遍接受,而不是 him/her。 (只是说)
  • OP 的数组是二维的(String[][])。他的方法基本上没问题,除了@ambigram_maker 指出的i &gt;= flags.length
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-11
  • 2012-09-17
  • 1970-01-01
  • 2020-08-28
  • 2013-07-11
相关资源
最近更新 更多