Java 是否为数组中的每个项目创建一个文件,并为另一个数组中的每个项目写入内容?

Java 是否为数组中的每个项目创建一个文件,并为另一个数组中的每个项目写入内容?,java,arrays,for-loop,Java,Arrays,For Loop,当我运行程序时,它会创建文件,但它会将每个文件的内容循环3次,而不是循环一次。我相信这就是我的for循环的设置方式 如何更正下面的程序,为一个数组fileNameAry中的每个项目创建一个文件,并使用另一个数组fileContentAry中的内容填充新文件的第一行,每个文件后面再添加3行,每个文件4行 确保每个文件只包含所需的4行代码的最佳方法是什么?如果此代码可以更好地组织或更高效地循环,我将如何执行此操作 /* * To change this license header, choose

当我运行程序时,它会创建文件,但它会将每个文件的内容循环3次,而不是循环一次。我相信这就是我的for循环的设置方式

如何更正下面的程序,为一个数组fileNameAry中的每个项目创建一个文件,并使用另一个数组fileContentAry中的内容填充新文件的第一行,每个文件后面再添加3行,每个文件4行

确保每个文件只包含所需的4行代码的最佳方法是什么?如果此代码可以更好地组织或更高效地循环,我将如何执行此操作

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package createfileloop;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;

/**
 *
 * @author DeveloperJC
 */
public class CreateFileLoop {
    public static void main(String[] args) throws IOException{  
    String[] fileNameAry = new String[]{
        "FirstFile.txt","SecondFile.txt","ThirdFile.txt"
    };
    String[] fileContentAry = new String[]{
        "First File","Second File","Third File"
    };
    int i,k;
        for(i=0; i<fileNameAry.length; i++){
            PrintStream fileStream = new PrintStream(new File("C:/Users/DeveloperJC/Desktop/"+fileNameAry[i]));
            for(k=0; k<fileContentAry.length; k++){
                fileStream.println("docname="+fileContentAry[k]);
                fileStream.println("2ndLine= Second Line");
                fileStream.println("3rdLine= Third Line");
                fileStream.println("4thLine= Fourth Line");
            }
        }
    }
}
不要为循环运行2,这会产生问题

因为两个字符串数组的大小相同,所以循环和

使用对应的数组名访问元素

请参阅下面修改的代码。希望它能解决你的问题

for(i=0; i<fileNameAry.length; i++){
            PrintStream fileStream = new PrintStream(new File("C:/Users/DeveloperJC/Desktop/"+fileNameAry[i]));

                fileStream.println("docname="+fileContentAry[i]);
                fileStream.println("2ndLine= Second Line");
                fileStream.println("3rdLine= Third Line");
                fileStream.println("4thLine= Fourth Line");

        }

对于在fork上迭代的每个文件=0;K到底哪里错了?更新了问题:确保每个文件只有4行的最佳方法,在4行之后,创建下一个文件。在第二个循环之后,您可能需要关闭fileStream。您可能更喜欢为每个循环使用一个。我相信你应该直截了当地问这个问题。
 fileStream.println("docname="+fileContentAry[i]);
 fileStream.println("2ndLine= Second Line");
 fileStream.println("3rdLine= Third Line");
 fileStream.println("4thLine= Fourth Line");