我是 Java 新手,一直在尝试实现一个创建目录及其各自文件的函数。其中一个文件是“mapping.txt”,它位于名为 NodeA 的文件夹中。mapping.txt 的内容是 NodeA 的绝对路径。
请在下面找到我尝试过的代码。为了更好地理解,我在所有可能的地方发表了评论。我想知道我无法在文件中写入的原因。任何帮助将不胜感激。
//-------------------------- To create Node and their respective Files ------------------------------------------------------
for(int j=0;j<alpha.length;j++){ //alpha is a String array which contains {"A","B","C","D"}
node_directory=Node.concat(alpha[j]); // nodde_directory is "C:\Users\Desktop\Node. I concat A,B,C and D to create different directories.
File dir = new File(node_directory);
if(!dir.exists()){
dir.mkdirs();
}
System.out.println("Path: \n" +dir.getAbsolutePath());
System.out.println();
List<String> fileList = Arrays.asList(files); // files is an array of string containing "mapping" and "data".
Iterator <String> iter = fileList.iterator(); //I traverse through the list.
while(iter.hasNext()){
File next_file = new File(node_directory+"\\"+iter.next()+".txt"); //while traversing, I append the current "iter.next" to "node_directory" and append ".txt" to create files.
System.out.println("The Files are: \n" +next_file);
System.out.println();
// I created the Directories, mapping and data Files for each directory.
/*I am stuck here, as it is not writing the path in the mapping File */
if(iter.next()=="mapping"){ // I check if iter.next is mapping, so that i can write in the mapping file, the path of Folder containing mapping file.
BufferedWriter br = new BufferedWriter(new FileWriter(next_file));
br.write(next_file.getAbsolutePath());
}
if(!next_file.exists()){
System.out.println(next_file.createNewFile());
}
我意识到发生了什么。因为我正在通过列表遍历字符串数组。问题出现在这里:
next_file = new File(node_directory+"\\"+iter.next()+".txt"); // This line creates files by appending the required data. Since iter.next() returns all the Files in one go,
BufferedWriter br = new BufferedWriter(new FileWriter(next_file));
br.write(dir.getAbsolutePath());
next_file 具有一次创建的所有文件。我需要知道创建后如何检查每个文件,以便编辑文件。
谢谢你。