Hi,

I'm currently trying to store all the text in text area into a txt file in directories using java. I know how 2 use mkdirs() to create directories, for example C:/d1/d2, but if i type

(new File(C:/d1/d2/sample.txt)).mkdirs()

it makes the txt file into a folder too. I tried with mkdir() too but failed. Is there any way to create d directories and txt file togather so i can store the information into it?
Below is my sample code:

public static void saveToTextFile(){
		String strFilePath = "C:/d1/d2/sample.txt";
		File f = new File(strFilePath);
		try{
			if(f.exists()){
				f.delete();	
			}else{
				f.mkdirs();
			}
			String s = textArea.getText();
	        FileWriter fw = new FileWriter(f);
	        fw.write(s);
	        fw.flush();
	        fw.close();
	        System.out.println("Data has been saved to C:/d1/d2/sample.txt");		
		}catch(IOException e){
			System.out.println("Error during writing");
		}
	}

I really appreciate for any help!
Cass

f.getParentFile().mkdirs();

The api docs work wonders, if you actually look at them.

You need to makedirs on C:/d1/d2 to set up the directory structure, then write your C:/d1/d2/sample.txt file to the directory.

You need to makedirs on C:/d1/d2 to set up the directory structure, then write your C:/d1/d2/sample.txt file to the directory.

I managed to run my code smoothly by following your advice. I tried a few times and finally i remove the following code then it runs normally.
Really thank both of u, especially James!

public static void saveToTextFile(){
		String strFilePath = "C:/d1/d2";
		File f = new File(strFilePath);
		try{
			f.mkdirs();
			//i close the following section
			/*if(f.exists()){
				f.delete();
				print("delete!");
			}*/
			String s = textArea.getText();
			File g = new File(strFilePath + "/xmlText.txt");
	        FileWriter fw = new FileWriter(g);
	        fw.write(s);
	        fw.flush();
	        fw.close();
	        print("Data has been saved to C:/d1/d2/sample.txt");	
		}catch(IOException e){
			System.out.println("Error during writing");
		}
	}

Is it really alright if I close the loop? I only worry that i might cause problem in the future..

That looks OK to me. Only suggestion is to put a full e.printStackTrace(); into your catch block so you can see the full text of any error message generated by Java.

That looks OK to me. Only suggestion is to put a full e.printStackTrace(); into your catch block so you can see the full text of any error message generated by Java.

Ok, thanks for your advice, James! Cheers!

maybe you solved exception, anyway you have to move fw.close(); from try block to the finally block (try - catch - finally)

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.