How to dynamically add text files to a given directory in Java?

I am using Eclipse. I want to read the number of XML files from a directory. Each XML file contains several body tags. I want to extract the values ​​of all body tags. My problem is that I have to save each body tag value (text) in a separate .txt file and add these text files to another given directory. Can you plz help, how can I create a dynamic .txt file and add them to the specified directory? Thanks in advance.

+5
source share
4 answers

First specify the path and directory name

File dir=new File("Path to base dir");
if(!dir.exists){
dir.mkdir();}

// then generate the file name

String fileName="generate required fileName";
File tagFile=new File(dir,fileName+".txt");
if(!tagFile.exists()){
tagFile.createNewFile();
}
+14
source

add import for java.io.File;

File f;
f=new File("myfile.txt");
if(!f.exists()){
f.createNewFile();

"myfile.txt" , , , "C:\\somedir\\yourfile.txt"

+2

- .

try {
    //Specify directory
    String directory = //TODO....
    //Specify filename
    String filename= //TODO....
    // Create file 
    FileWriter fstream = new FileWriter(directory+filename+".txt");
    BufferedWriter out = new BufferedWriter(fstream);
    //insert your xml content here
    out.write("your xml content");
} catch (Exception e) {
    System.err.println("Error: " + e.getMessage());
} finally {
    //Close the output stream
    out.close();
}
+1
source

It is not clear why you mentioned the XML part. But it seems that you can get text from an XML file and want to write it to a separate text file.

Read this basic guide to creating, reading, and writing files in Java: http://download.oracle.com/javase/tutorial/essential/io/file.html

Path logfile = ...;

//Convert the string to a byte array.
String s = ...;
byte data[] = s.getBytes();

OutputStream out = null;
try {
    out = new BufferedOutputStream(logfile.newOutputStream(CREATE, APPEND));
    ...
    out.write(data, 0, data.length);
} catch (IOException x) {
    System.err.println(x);
} finally {
    if (out != null) {
        out.flush();
        out.close();
    }
}
+1
source

All Articles