I need to write a code in which i want to create each file for every iteration of a loop add data into the file. also the filename should change every time.
for example: familyname1_parts.txt for 1 iteration for second
familyname2.parts.txt for 2 iteration and so on..

try
    	{
    		 out = new FileOutputStream(set.fileLoc + "" +set.fileName,true);
    		
    		p = new PrintStream( out );

here fileloc and set.filename is fetched from a properties file..

earlier all data was added to the same file.

How can we change file name everytime?

Dani AI

Generated

As suggested, the core idea is to change the filename inside the loop. Below is a concise, modern Java pattern (Java 7+) that generates a safe filename from each family name returned by your query, ensures the output directory exists, creates a new file per iteration, and writes to it using try-with-resources so streams are always closed.

import java.nio.file.*;
import java.nio.charset.StandardCharsets;
import java.io.IOException;
import java.io.BufferedWriter;

String family = /* value from query */;
String safe = family.replaceAll("[^A-Za-z0-9._-]", "_");
Path dir = Paths.get(set.fileLoc);
Files.createDirectories(dir);
Path file = dir.resolve(safe + "_part.txt");

try (BufferedWriter w = Files.newBufferedWriter(file, StandardCharsets.UTF_8,
        StandardOpenOption.CREATE_NEW)) {
    w.write("data for " + family);
}

Notes and troubleshooting: use CREATE_NEW to force a fresh file (FileAlreadyExistsException if it exists); use CREATE + TRUNCATEEXISTING to overwrite or CREATE + APPEND to append. Sanitize family names to remove OS-invalid characters and check write permissions on set.fileLoc. If names may repeat, append a counter or timestamp (e.g., safe + "" + counter + ".txt") to avoid collisions. For (C#): same pattern — use Path.Combine, sanitize with Path.GetInvalidFileNameChars, and write inside a using(StreamWriter) block.

Recommended Answers

All 5 Replies

In your loop keep a counter, then make a file name something like this:

String fileName = "familyname" + counter + ".parts.txt2;

Hi James,

Thank you very much for responding so soon. I need to accomplish these things in each iteration.

1. create a new file for every iteration.
2. file name should change like this psoc_part.txt , usb_part.txt . i mean technically Sting[abc]_part.txt means this should change dynamically each time.
like this many families are there for each family i need each file to be created along with filename.

i want this code to be in loop to create a new file wenever the family name is matched in which i take it from a query.
sorry for not explaining this in my previous thread.

i will change file name by myself .But i need help on creating creting new file everytime. plz kindly help

FileOutputStream out; 
                PrintStream ps; // declare a print stream object
                try {
                 // Create a new file output stream
                out = new FileOutputStream("myfile.txt");

                        // Connect print stream to the output stream
                        ps = new PrintStream(out);
    
                        ps.println ("This data is written to a file:");
            System.err.println ("Write successfully");
                        ps.close();
                }

What's the problem in creating a new file? You've already got the code:

new FileOutputStream(fileName);

You can do that in your loop if fileName changes on each iteration.

Yes, I did it. Thanks a lot.. :-)

how would this be done in C#? I was thinking about creating a method for it.

Thanks,
Linez

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.