import java.io.*;
public class StringToFileWriterMain {
public static void main(String[] args) {
try {
// the buffered reader
BufferedReader myBufferedReader = new BufferedReader(new InputStreamReader(System.in));
// the string to write
System.out.println("Type string to write");
String stringToWrite = myBufferedReader.readLine();
// the file to write to
System.out.println("Type file to write to");
String fileToWriteTo = myBufferedReader.readLine();
ThingToThingWriter myThingToThingWriter = ThingToThingWriterFactory.createThingToThingWriter("String", "File");
myThingToThingWriter.writeThingToThing(stringToWrite, fileToWriteTo);
} catch(Exception e) {
System.out.println("ERROR OCCURRED");
}
}
}
interface ThingToThingWriter {
public boolean writeThingToThing(String thing1, String thing2);
}
class StringToFileWriter implements ThingToThingWriter {
protected StringToFileWriter() {
// constructor
}
/**
* Writes stringToWrite to fileToWriteTo.
* Returns true if stringToWrite is a long string.
*/
public boolean writeThingToThing(String stringToWrite, String fileToWriteTo) {
try {
BufferedWriter myBufferedWriter = new BufferedWriter(new FileWriter(fileToWriteTo));
myBufferedWriter.write(stringToWrite);
myBufferedWriter.close();
if(getLengthOfString(stringToWrite) > 17.0) {
return true;
} else {
return false;
}
} catch(Exception e) {
System.out.println("ERROR OCCURRED");
return false;
}
}
// returns a double because the string might be too long for an integer
private double getLengthOfString(String stringToGetLengthOf) {
double lengthOfString = 0.0;
try {
while(true) {
stringToGetLengthOf.charAt((int) lengthOfString);
lengthOfString = lengthOfString + 1.0;
}
} catch(Exception e) {
return lengthOfString;
}
}
}
class ThingToThingWriterFactory {
public static ThingToThingWriter createThingToThingWriter(String thing1Type, String thing2Type) {
if(thing1Type.equalsIgnoreCase("String") && thing2Type.equalsIgnoreCase("File")) {
return new StringToFileWriter();
} else {
throw new RuntimeException("WRITING THINGS OF TYPE "+thing1Type+" TO THINGS OF TYPE "+thing2Type+" IS NOT YET SUPPORTED");
}
}
}