I'm trying to create a file name that uses the date and time from another class to name it, problem is the class is called every so often and when it is a new file is created. I just wanted to create the file once and then write to it all the time. Is it possible to do this as I can't work out how to?
Many thanks for any help in advance!
public void fileOutputToFile(String hex) throws Exception{
dateAndTime dat = new dateAndTime();
String date = dat.currentDateAndTime();
String fileInfo = hex;
String fileName = (date+".tsv");
try{
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName, true)));
out.print(fileInfo);
out.print("\t");
out.close();
}catch (IOException e){
}
}
Use a date formatter like SimpleDateFormat to format the date to a string, e.g. "yyyy" to make a file 2011.tsv. Note that this requires a Date object to be returned.
If you don't want to use a file based on date, store the filename somewhere. But why would you then use the date as the filename in the first place?
Edit: For a new file every hour, use a format like this: yyyy-MM-dd_HH (would result in 2011-03-29_17.tsv for example).
On the first call, you could store the filename as a member of the class.
You can append to the file on subsequent calls by using the FileWriter constructor:
public FileWriter( String fileName,
boolean append)
If you write frequently, an alternative is to keep the file open, storing the PrintWriter as a member. However, this may preclude some external interactions with the file in between writes.
Can you save the file name in session? if the file name exists in session use that other wise create it from another clases..
The problem with using the time alone is you can have still have multiple creates created at the same time.
You can do the following.
// not thread safe.
private static final DateFormat DF = new SimpleDateFormat("yyyyMMdd_HHmmss_SSS")
File file;
do {
file = new File(DF.format(new Date())+".tsv");
} while(!file.createNewFile());
FileUtils.writeStringToFile(file, hex+"\t");
The other problem is that you will giving the file a new name on every update. If youw ant to keep the same file name you need to set this in a different method of lazy initialise the value from a field.
In order to avoid creating a new file with a new date and time every time a client application invokes method fileOutputToFile(), move all lines up to and including the creation of the PrintWriter to the constructor so that the constructor opens the file just once and method fileOutputToFile() appends fileInfo to the output stream.
Make sure to add a method close() that closes the PrintWriter stream by invoking out.close().
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class MyLoggingClass {
private PrintWriter out;
public MyLoggingClass() throws IOException {
dateAndTime dat = new dateAndTime();
String date = dat.currentDateAndTime();
String fileName = (date + ".tsv");
out = new PrintWriter(
new BufferedWriter(new FileWriter(fileName, true)));
}
public void fileOutputToFile(String hex) {
String fileInfo = hex;
out.print(fileInfo);
out.print("\t");
}
public void close() {
out.close();
}
}
Related
I am trying to write data to a binary file and am having difficulty. When I run this method I don't get any output to the file. Also when it comes to writing my "Date" object, I can't seem to find a write method that takes it as a parameter. The object consists of an int month, day, and year. How can I write it into a binary file properly?
Also, does "File" work for binary as well? I have only previously used it for regular .txt files and I'm not sure if it can be used the same way in this situation. Thanks!
Here is my write method:
private void writeBinary(){
//String fileName = getUserInput();
String fileTest = "BinaryMonster.bin";
File file = new File(fileTest);
DataOutputStream out;
try{
out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file, true)));
if(!(file.exists())){
file.createNewFile();
System.out.println("New file created...");
}
for(int i = 0; i < monsterAttacks.size(); i++){
out.writeInt(monsterAttacks.get(i).getID());
out.write(monsterAttacks.get(i).getDate()); //getting error
out.writeUTF(monsterAttacks.get(i).getName() + monsterAttacks.get(i).getLocation() + monsterAttacks.get(i).getReporter());
}
} catch(IOException e) {
e.printStackTrace();
}
}
It is giving error because you are writing whole object of date into the file using DataOutputStream, which don't allow you to do that.
Write it in the form of String into the file. It will be better.
out.writeUTF(monsterAttacks.get(i).getDate().toString());
But if you want to save the whole object into the file, then you need to use ObjectOutputStream which write whole serialized objects into the file.
And it is better approach to flush and close the file.
out.flush();
out.close();
I am wondering what the best way to clear a file is. I know that java automatically creates a file with
f = new Formatter("jibberish.txt");
s = new Scanner("jibberish.txt");
if none already exists. But what if one exists and I want to clear it every time I run the program? That is what I am wondering: to say it again how do I clear a file that already exists to just be blank?
Here is what I was thinking:
public void clearFile(){
//go through and do this every time in order to delete previous crap
while(s.hasNext()){
f.format(" ");
}
}
Best I could think of is :
Files.newBufferedWriter(pathObject , StandardOpenOption.TRUNCATE_EXISTING);
and
Files.newInputStream(pathObject , StandardOpenOption.TRUNCATE_EXISTING);
In both the cases if the file specified in pathObject is writable, then that file will be truncated. No need to call write() function. Above code is sufficient to empty/truncate a file.This is new in java 8.
Hope it Helps
You could delete the file and create it again instead of doing a lot of io.
if(file.delete()){
file.createNewFile();
}else{
//throw an exception indicating that the file could not be cleared
}
Alternately, you could just overwrite the contents of the file in one go as explained in the other answers :
PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.close();
Also, you are using the constructor from Scanner that takes a String argument. This constructor will not read from a file but use the String argument as the text to be scanned. You should first created a file handle and then pass it to the Scanner constructor :
File file = new File("jibberish.txt");
Scanner scanner = new Scanner(file);
If you want to clear the file without deleting may be you can workaround this
public static void clearTheFile() {
FileWriter fwOb = new FileWriter("FileName", false);
PrintWriter pwOb = new PrintWriter(fwOb, false);
pwOb.flush();
pwOb.close();
fwOb.close();
}
Edit: It throws exception so need to catch the exceptions
You can just print an empty string into the file.
PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.close();
type
new PrintWriter(PATH_FILE).close();
Better to use this:
public static void clear(String filename) throws IOException {
FileWriter fwOb = new FileWriter(filename, false);
PrintWriter pwOb = new PrintWriter(fwOb, false);
pwOb.flush();
pwOb.close();
fwOb.close();
}
I have been looking for the past hour or so trying to find the reason for this, but have found nothing. It is a very small text file (only 4 characters at most), thus the reason I did not bother with a BufferedReader or BufferedWriter. The problem lies in the fact that while I have the writer put the variable into the file and even close the file, it does not actually keep the change in the file. I have tested this by checking the file immediately after running the method containing this code.
try {
int subtract = Integer.parseInt(secMessage[2]);
try {
String deaths = readFile("C:/Users/Samboni/Documents/Stuff For Streaming/deaths.txt", Charset.defaultCharset());
FileWriter write = new FileWriter("C:/Users/Samboni/Documents/Stuff For Streaming/deaths.txt");
int comb = Integer.parseInt(deaths) - subtract;
write.write(comb);
write.close();
sendMessage(channel, "Death count updated to " + comb);
} catch (IOException e) {
e.printStackTrace();
}
} catch (NumberFormatException e) {
e.printStackTrace();
sendMessage(channel, "Please use numbers to modify death count");
}
EDIT: Since it was asked, here is my readFile message:
static String readFile(String path, Charset encoding) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
I have already tested it and it returns the contents without error.
EDIT2: Posting the readFile method made me think of something to try, so I removed the call to it (code above also updated) and tried it again. It now writes to the file, but does not write what I want. New question will be made for this.
FileWriter write = new FileWriter(readFile("C:/Users/Samboni/Documents/Stuff For Streaming/deaths.txt", Charset.defaultCharset()));
You're trying to write a file named after the contents of deaths.txt. It's possible that you intend to be writing to the file itself.
From http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html
FileWriter(String fileName)
Constructs a FileWriter object given a file name.
FileWriter write = new FileWriter(readFile("C:/Users/Samboni/Documents/Stuff For Streaming/deaths.txt", Charset.defaultCharset()));
Currently you are using the contents of the file instead of the file name.
I wrote a simple program to read the content from text/log file to html with conditional formatting.
Below is my code.
import java.io.*;
import java.util.*;
class TextToHtmlConversion {
public void readFile(String[] args) {
for (String textfile : args) {
try{
//command line parameter
BufferedReader br = new BufferedReader(new FileReader(textfile));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
Date d = new Date();
String dateWithoutTime = d.toString().substring(0, 10);
String outputfile = new String("Test Report"+dateWithoutTime+".html");
FileWriter filestream = new FileWriter(outputfile,true);
BufferedWriter out = new BufferedWriter(filestream);
out.write("<html>");
out.write("<body>");
out.write("<table width='500'>");
out.write("<tr>");
out.write("<td width='50%'>");
if(strLine.startsWith(" CustomerName is ")){
//System.out.println("value of String split Client is :"+strLine.substring(16));
out.write(strLine.substring(16));
}
out.write("</td>");
out.write("<td width='50%'>");
if(strLine.startsWith(" Logged in users are ")){
if(!strLine.substring(21).isEmpty()){
out.write("<textarea name='myTextBox' cols='5' rows='1' style='background-color:Red'>");
out.write("</textarea>");
}else{
System.out.println("else if block:");
out.write("<textarea name='myTextBox' cols='5' rows='1' style='background-color:Green'>");
out.write("</textarea>");
} //closing else block
//out.write("<br>");
out.write("</td>");
}
out.write("</td>");
out.write("</tr>");
out.write("</table>");
out.write("</body>");
out.write("</html>");
out.close();
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
}
public static void main(String args[]) {
TextToHtmlConversion myReader = new TextToHtmlConversion();
String fileArray[] = {"D:/JavaTesting/test.log"};
myReader.readFile(fileArray);
}
}
I was thinking to enhance my program and the confusion is of either i should use Maps or properties file to store search string. I was looking out for a approach to avoid using substring method (using index of a line). Any suggestions are truly appreciated.
From top to bottom:
Don't use wildcard imports.
Don't use the default package
restructure your readFile method in more smaller methods
Use the new Java 7 file API to read files
Try to use a try-block with a resource (your file)
I wouldn't write continuously to a file, write it in the end
Don't catch general Exception
Use a final block to close resources (or the try block mentioned before)
And in general: Don't create HTML by appending strings, this is a bad pattern for its own. But well, it seems that what you want to do.
Edit
Oh one more: Your text file contains some data right? If your data represents some entities (or objects) it would be good to create a POJO for this. I think your text file contains users (right?). Then create a class called Users and parse the text file to get a list of all users in it. Something like:
List<User> users = User.parse("your-file.txt");
Afterwards you have a nice user object and all your ugly parsing is in one central point.
public class Customer {
public static void main(String[] args) throws IOException {
FileOutputStream a = new FileOutputStream("customer.txt");
ObjectOutputStream b = new ObjectOutputStream(a);
human Iman = new human("Iman",5000);
human reda = new human("reda",5555);
b.writeObject(Iman); //prints random symbols.
b.writeObject(reda);
}
}
class human implements Serializable{
private String name;
private double balance;
public human(String n,double b){
this.name=n;
this.balance=b;
}
}
What do these random symbols represent?
Yes, you are trying to store the object itself and hence binary format is getting stored.
To actually store the data in text format, use below code BufferedWriter as below:
public void writeHumanStateToFile(Human human){
try{
File file = new File("filename.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(human.getName);
bw.write(human.getBalance);
bw.newLine();
bw.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
I am assuming you want to persist the state of Human object.
You're using ObjectOutputStream. That doesn't produce text - it produces a binary serialized version of the data. If you really need a text representation, you'll need to use a different approach.
If you're fine with it being binary data though, leave it as it is - but perhaps change the filename to be less misleading. You can read the data again with ObjectInputStream.
The data format is described in the Object Serialization Stream Protocol document. As you've noted, it's not human-readable.
If you want to serialize in a readable format, you might be able to use java.beans.XMLEncoder, or something like Pojomatic.
You are serializing the object. It is not meant to be readable in plain text, but to be a binary format that makes it easy to read the object and recreate it in a later execution of the program.
If you want to store your objects in plain text, then you need to write the individual fields of your object to the file.