How to convert a String into a File Object in java? - java

I have file contents in a java string variable, which I want to convert it into a File object is that possible?
public void setCfgfile(File cfgfile)
{
this.cfgfile = cfgfile
}
public void setCfgfile(String cfgfile)
{
println "ok overloaded function"
this.cfgfile = new File(getStreamFromString(cfgfile))
}
private def getStreamFromString(String str)
{
// convert String into InputStream
InputStream is = new ByteArrayInputStream(str.getBytes())
is
}

As this is Groovy, you can simplify the other two answers with:
File writeToFile( String filename, String content ) {
new File( filename ).with { f ->
f.withWriter( 'UTF-8' ) { w ->
w.write( content )
}
f
}
}
Which will return a file handle to the file it just wrote content into

Try using the apache commons io lib
org.apache.commons.io.FileUtils.writeStringToFile(File file, String data)

You can always create a File object from a String using the File(String) constructor. Note that the File object represents only an abstract path name; not a file on disk.
If you are trying to create an actual file on disk that contains the text held by the string there are several classes that you can use, for example:
try {
Writer f = new FileWriter(nameOfFile);
f.write(stringToWrite);
f.close();
} catch (IOException e) {
// unable to write file, maybe the disk is full?
// you should log the exception but printStackTrace is better than nothing
e.printStackTrace();
}
FileWriter will use the platform default encoding when converting the characters of the string to bytes that can be written on disk. If this is a problem you can use a different encoding by wrapping FileOutputStream inside an OutputStreamWriter. For example:
String encoding = "UTF-8";
Writer f = new OutputStreamWriter(new FileOutputStream(nameOfFile), encoding);

To write a String to a file, you usually should use a BufferedWriter:
private writeToFile(String content) {
BufferedWriter bw;
try {
bw = new BufferedWriter(new FileWriter(this.cfgfile));
bw.write(content);
}
catch(IOException e) {
// Handle the exception
}
finally {
if(bw != null) {
bw.close();
}
}
}
Besides, the new File(filename) simply instanciates a new File object with the name filename (it does not actually create the file on your disk). Therefore, you statement:
this.cfgfile = new File(getStreamFromString(cfgfile))
will simple instanciate a new File with the name the String returned by the this.cfgfile = new File(getStreamFromString method.

Related

How to load a tsv file for MALLET using FileInputStream in Java?

I want to load the flat text file passed in as 'TMFlatFile' (which is the .tsv file format to use in MALLET) into into the fileReader variable.
I have created the method, RunTopicModelling() and am having a problem with the try/except block.
I have created my File and FileInputStream objects, but dont know how to load it correctly into fileReader?
I have an error that "The method read(CharBuffer) in the type InputStreamReader is not applicable for the arguments (int)".
public class TopicModelling {
private void StartTopicModellingProcess(String filePath) {
JSONIOHelper jsonIO = new JSONIOHelper();
jsonIO.LoadJSON(filePath);
ConcurrentHashMap<String, String> lemmas = jsonIO.GetDocumentsFromJSONStructure();
SaveLemmaDataToFile("topicdata.txt" ,lemmas);
}
private void SaveLemmaDataToFile(String TMFlatFile, ConcurrentHashMap<String, String> lemmas) {
for (Entry<String, String> entry : lemmas.entrySet()) {
try (FileWriter writer = new FileWriter(TMFlatFile)) {
;
writer.write(entry.getKey() + "\ten\t" + entry.getValue() + "\r\n");
} catch (Exception e)
{
System.out.println("Saving to flat text file failed...");
}
}
}
private void RunTopicModelling(String TMFlatFile, int numTopics, int numThreads, int numIterations) {
ArrayList<Pipe> pipeList = new ArrayList <Pipe>();
// Pipes: tokenise, map to features
pipeList.add(new CharSequence2TokenSequence (Pattern.compile("\\p{L}[\\p{L}\\p{P}]+\\p{L}")));
pipeList.add(new TokenSequence2FeatureSequence());
InstanceList instances = new InstanceList (new SerialPipes(pipeList));
InputStreamReader fileReader = null;
//loads the file passed in via the TMFlatFile variable into the fileReader variable - this block I have a problem with
try {
File inFile = new File(TMFlatFile);
FileInputStream fis = new FileInputStream(inFile);
int line;
while ((line = fis.read()) != -1) {
}
fileReader.read(line);
}
fis.close();
}catch(
Exception e)
{
System.out.println("File Load Failed");
System.exit(1);
}
\\ // linking data to the pipeline
instances.addThruPipe(new CsvIterator(fileReader,Pattern.compile("^(\\S*)[\\s,]*(\\S*)[\\s,]*(.*)$"),3,2,1));
}
Can someone tell me what is the correct way to do this?
It's hard to say what the immediate issue is because the code sample provided looks like it's missing important parts, and would not compile as written (for example Exception e) and regex without quotes).
The data import developers guide https://mimno.github.io/Mallet/import-devel has sample code that should be a good starting point.

How to avoid saving a file on hard drive?

Each time I run the following code, the file is saved on a hard drive. However, I want it to be saved only in the Object Storage container.
OSClient os = OSFactory.builder()
.endpoint("...")
.credentials("...","...")
.tenantName("...")
.authenticate();
String containerName = "MyImgs";
String objectName = "test.jpg";
BufferedWriter output = null;
try {
File f = new File(objectName);
output = new BufferedWriter(new FileWriter(f));
output.write(text);
String etag = os.objectStorage().objects().put(containerName,
objectName,
Payloads.create(f));
} catch ( IOException e ) {
e.printStackTrace();
}
UPDATE:
I am using this API.
Looking at the Javadoc for Payloads it has a method which takes in InputStream. To read an String as an InputStream you can do
Payloads.create(new ByteArrayInputStream(text.getBytes());
This will avoid the need to create a file just so you have something to read.
From reading the OpenStack4j API it is possible to create a payload from an InputStream, so why don't you do that instead of from a File?
Convert the text to an InputStream with a helper function like this:
private static InputStream newInputStreamFrom(String text) {
try {
return new ByteArrayInputStream(text.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new AssertionError(); // should not occur
}
}
And then your code could look something like this:
OSClient os = OSFactory.builder()
.endpoint("...")
.credentials("...","...")
.tenantName("...")
.authenticate();
String containerName = "MyImgs";
String objectName = "test.jpg";
InputStream stream = newInputStreamFrom(text);
String etag = os.objectStorage().objects().put(containerName,
objectName,
Payloads.create(stream));

Writing Into a file using Java

public static void writeIntoFile() {
FileOutputStream fileOutputStream = null;
ObjectOutputStream objectOutputStream = null;
try {
fileOutputStream = new FileOutputStream("Employee.txt");
objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(list1);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileOutputStream == null) {
System.out.println("file is not created");
}
if (objectOutputStream == null) {
System.out.println("cant able to write");
}
}
}
I want to using this function to writing in a file. it writes successfully but it display data in bytecode. how can I save it into string format?
Use a FileWriter wrapped inside a BufferedWriter to write character data to a File.
ObjectOutputStream is used for serialization and results in a binary encoded file. Its only useful if you only want to load the file through your program and do not wish to read its contents elsewhere like in an external editor.
You also need to iterate through your List and save the requisite properties of your underlying Object in a format you wish to parse your File later on in. For example, as CSV (comma separated values) every Employee object and its properties would be persisted as one single line in the output file.
BufferedWriter br = new BufferedWriter(new FileWriter("Employee.csv"));
for (Employee employee : list) {
br.write(employee.getFName() + ", " + employee.getLName());
br.newLine();
}
br.close();
in the function writeIntoFile is write a Serialization Object into file
you should use the object's toString() to write a String into file
you can change bytecode into string using one simple way.
pass the bytecode into string constructor
like this:
new String(bytecode object);
and then write string object into file.

How to Write text file Java

The following code does not produce a file (I can't see the file anywhere).
What is missing?
try {
//create a temporary file
String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(
Calendar.getInstance().getTime());
File logFile=new File(timeLog);
BufferedWriter writer = new BufferedWriter(new FileWriter(logFile));
writer.write (string);
//Close writer
writer.close();
} catch(Exception e) {
e.printStackTrace();
}
I think your expectations and reality don't match (but when do they ever ;))
Basically, where you think the file is written and where the file is actually written are not equal (hmmm, perhaps I should write an if statement ;))
public class TestWriteFile {
public static void main(String[] args) {
BufferedWriter writer = null;
try {
//create a temporary file
String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
File logFile = new File(timeLog);
// This will output the full path where the file will be written to...
System.out.println(logFile.getCanonicalPath());
writer = new BufferedWriter(new FileWriter(logFile));
writer.write("Hello world!");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Close the writer regardless of what happens...
writer.close();
} catch (Exception e) {
}
}
}
}
Also note that your example will overwrite any existing files. If you want to append the text to the file you should do the following instead:
writer = new BufferedWriter(new FileWriter(logFile, true));
I would like to add a bit more to MadProgrammer's Answer.
In case of multiple line writing, when executing the command
writer.write(string);
one may notice that the newline characters are omitted or skipped in the written file even though they appear during debugging or if the same text is printed onto the terminal with,
System.out.println("\n");
Thus, the whole text comes as one big chunk of text which is undesirable in most cases.
The newline character can be dependent on the platform, so it is better to get this character from the java system properties using
String newline = System.getProperty("line.separator");
and then using the newline variable instead of "\n". This will get the output in the way you want it.
In java 7 can now do
try(BufferedWriter w = ....)
{
w.write(...);
}
catch(IOException)
{
}
and w.close will be done automatically
It's not creating a file because you never actually created the file. You made an object for it. Creating an instance doesn't create the file.
File newFile = new File("directory", "fileName.txt");
You can do this to make a file:
newFile.createNewFile();
You can do this to make a folder:
newFile.mkdir();
Using java 8 LocalDateTime and java 7 try-with statement:
public class WriteFile {
public static void main(String[] args) {
String timeLog = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss").format(LocalDateTime.now());
File logFile = new File(timeLog);
try (BufferedWriter bw = new BufferedWriter(new FileWriter(logFile)))
{
System.out.println("File was written to: " + logFile.getCanonicalPath());
bw.write("Hello world!");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
You can try a Java Library. FileUtils, It has many functions that write to Files.
It does work with me. Make sure that you append ".txt" next to timeLog. I used it in a simple program opened with Netbeans and it writes the program in the main folder (where builder and src folders are).
The easiest way for me is just like:
try {
FileWriter writer = new FileWriter("C:/Your/Absolute/Path/YourFile.txt");
writer.write("Wow, this is so easy!");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
Useful tips & tricks:
Give it a certain path:
new FileWriter("C:/Your/Absolute/Path/YourFile.txt");
New line
writer.write("\r\n");
Append lines into existing txt
new FileWriter("log.txt");
Hope it works!

Write problem - lossing the original data

Every time I write to the text file I will lose the original data, how can I read the file and enter the data in the empty line or the next line which is empty?
public void writeToFile()
{
try
{
output = new Formatter(myFile);
}
catch(SecurityException securityException)
{
System.err.println("Error creating file");
System.exit(1);
}
catch(FileNotFoundException fileNotFoundException)
{
System.err.println("Error creating file");
System.exit(1);
}
Scanner scanner = new Scanner (System.in);
String number = "";
String name = "";
System.out.println("Please enter number:");
number = scanner.next();
System.out.println("Please enter name:");
name = scanner.next();
output.format("%s,%s \r\n", number, name);
output.close();
}
You must open the file for append.
You need to open myFile in append mode. See this link for an example.
As others have said, use the append option.
This code can write data in the default platform encoding:
private static void appendToFile() throws IOException {
boolean append = true;
OutputStream out = new FileOutputStream("TextAppend.txt", append);
Closeable resource = out;
try {
PrintWriter pw = new PrintWriter(out);
resource = pw;
pw.format("%s,%s %n", "foo", "bar");
} finally {
resource.close();
}
}
There are a number of classes you can wrap around an OutputStream to achieve the same effect. Be aware that the above approach can lose data when the code is run on a platform that doesn't use a Unicode default encoding (like Windows) and may produce different output on different PCs.
One case in which care is need is if the encoding inserts a byte order mark. If you wanted to write lossless Unicode text in UTF-16 marked with a little-endian BOM, you would need to check the file for existing data.
private static void appendUtf16ToFile() throws IOException {
File file = new File("TextAppend_utf16le.txt");
String encoding = (file.isFile() && file.length() > 0) ?
"UnicodeLittleUnmarked" : "UnicodeLittle";
boolean append = true;
OutputStream out = new FileOutputStream(file, append);
Closeable resource = out;
try {
Writer writer = new OutputStreamWriter(out, encoding);
resource = writer;
PrintWriter pw = new PrintWriter(writer);
resource = pw;
pw.format("%s,%s %n", "foo", "bar");
} finally {
resource.close();
}
}
Supported encodings:
Java 6
Java 5
We're you've got: new Formatter(myFile); you'll want to use new Formatter(new FileWriter(myfile, true). The true indicates you want to append to that file.

Categories

Resources