i worte this code about a month ago, it creates a directory or file and then saves data to it, it just makes ur life easier instead of doing it manually, i cheacked this code earlier today it seems fine.
I am giving you 100% permission to use this code, if you wish to post it somewhere else be my guest, but i would like credits.
Code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
/*--------------------------------------------------------------------------
//Author List:
// Ikram <Creator>
//
//Description:
// A sample code that creates a directory, a file and saves data to the file.
// There is plenty of room for improvement but i don't have a lot of time at the moment..
// *update* the application does now write more than one line in the textfile and ends when the user types "stop".
//
//Environment:
// This software was developed using Eclipse and Java 1.6
//
//Copyright Information:
// Copyright (C) 2009 <Institution><None>
// Ikram www.rspsoft.org
//
//----------------------------------------------------------------------*/
public class CreateDirs{
public static void main(String[] args) {
// create directory
File fDir = new File("c:\\tmpfile");
if (fDir.exists()){
System.out.println("Dir already exists!");
}
else{
System.out.println("Creating directory!");
fDir.mkdir();
}
// create empty file
String sDir = fDir.toString();
File fFile = new File(sDir + "\\File.txt");
try {
fFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(sDir);
// type text
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = ""; //initialize the string.. , don't forget to initialize a variable..
System.out.println("Type \"stop\" to stop the application.");
System.out.print("Type text: ");
try {
s = br.readLine(); //reads a line at the time.. look how to read more at once.. *update* works now
// add data to file
FileWriter fw = new FileWriter(sDir + "\\File.txt");
BufferedWriter bw = new BufferedWriter(fw);
while (!s.equals("stop")){
s = br.readLine();
if (!s.equals("stop")) // do not write stop into the textfile
bw.write(s); //write user typed data
bw.newLine();
//System.out.println("Typed: " + s);
}
// test if it writes to a file.
//bw.newLine();
//bw.write("hard coded text --++--++--");
bw.close();
System.out.println("Data saved in: " + sDir + "\\File.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
credits- Ikram, HappyFace