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();
Related
I have two csv files
File 1:
ID,NAME
1,FOO
2,BAR
3,XYZ
File 2:
ID,NAME,DOB
3,XYZ,02/03/1999
4,BAR,01/01/1995
1,FOO,01/01/1996
How can I select rows from CSV File 2 which has columns ID,NAME value matched in File 1 in java language.
Expected Result:
ID,NAME,DOB
3,XYZ,02/03/1999
1,FOO,01/01/1996
Basically you want to perform Vlookup operation .
You can get desired outcome by using Apache POI library. This library provides set of methods to perform Vlookup.
You can refer to the below resources for detailed understanding.
https://poi.apache.org/apidocs/dev/org/apache/poi/ss/formula/functions/Vlookup.html
There are a lot of API's that support functions like comparing .csv files. However, Java also has its own ways to do this.
I'll explain it step by step:
First, you should read the two files into the program. java.io provides some classes with this functionality.
Then, after the content of both files is stored in an appropriate data structure, you can compare them.
You can then simply store the matching lines in another data structure and return them.
Last but not least, you also have to write to a new or already existing file using classes from java.io.
Here is a method to read in files:
public ArrayList<String> readInFile(String absoluteFilePath) {
BufferedReader reader = null;
ArrayList<String> csvContent = new ArrayList<>();
String currentLine;
try {
reader = new BufferedReader(new FileReader(absoluteFilePath));
while((currentLine = reader.readLine()) != null) {
csvContent.add(currentLine);
}
reader.close();
}
catch (Exception e) {
e.printStackTrace();
}
return csvContent;
}
The method uses a BufferedReader to read the file and adds it line by line to the ArrayList
Writing to a .csv file is just as easy as reading from one. You just have to decide whether you want to write to an existing file or to a file that already exists.
Here is a method to write into files:
public void writeToFile(ArrayList<String> csvContent, String absoluteFilePath) {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(absoluteFilePath));
for (int i = 0; i < csvContent.size(); i++) {
writer.write(csvContent.get(i) + "\n");
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
This method uses a BufferedWriter to either create a file at the given path or overwrite an existing one and writes the contents of the ArrayList into the file.
Good luck!
I am attempting to pull some values from a webpage, with the intention of writing them into a .txt file for manual validation. I have looked around the web and cannot find the way to achieve this in my scenario. I will be writing the code in java if possible.
I have the following html code available for the element:
<td class="value" data-bind="text:
$data.value">Windows Server 2012 R2 Standard 64-bit</td>
And the xpath for the element is:
html/body/div[4]/div/div[4]/div[2]/div[4]/div/div[1]/div[1]/table[1]/tbody/tr[2]/td[2]
Is anyone able to help me create a sample piece of code that will;
a) Pick up the value and write it into a text file. Preferably with a prefix of 'Operating system'.
b) Save the file with a unique ID, My thought is to suffix the filename with a datetime stamp.
c) I will have multiple elements to read from the webpage and then write to the text file, around 8 or so, is there any consideration I need to be aware of for writing multiple values to a .txt file and format them neatly?
Hopefully I have included everything I need to here, if not just ask!
Many thanks in advance. KG
Thats not as difficult as it seems. I use similar function for me to write a log into a txt file.
At first I would write all Information in one String variable. It's helpful to format the Information before writing it into the variable. If you collect all Informations your could write this String very simple to a txt file using the following Code:
private static void printToTxt(){
String info = "Collected Informations";
String idForTxtFile = new SimpleDateFormat("dd.MM.yyyy_HH.mm.ss").format(new Date());
File file = new File("Filename" + idForTxtFile);
try {
FileWriter fw = new FileWriter(file, true);
//if you want to write the linesperator ("\n) as they are in the txt you should use the following Code:
String lineSeparator = System.getProperty("line.separator");
String[] ouput = info.split("\n");
for (int i = 0; i <= output.length-1; i++) {
fw.write(output[i]);
fw.write(lineSeparator);
}
//instead you could only use:
fw.write(info);
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println(e.getLocalizedMessage);
}
Little bit late, but here is my version, maybe you could use some additional to yours!
I have reviewed the answers on the question How do I create a file and write to it in Java?, thanks for the nudge #Mardoz, and with some playing around I have it doing what I needed. Here is the final code, with the date also being tagged into the filename:
Date date = new Date() ;
SimpleDateFormat dateFormat = new SimpleDateFormat("DD-MM-yyyy HH-mm") ;
// Wait for the element to be available
new WebDriverWait(Login.driver,10).until(ExpectedConditions.visibilityOfElementLocated
(By.xpath("html/body/div[4]/div/div[4]/div[2]/div[4]/div/div[1]/div[1]/table[1]/tbody/tr[2]/td[2]")));
Writer writer = null;
// Find the value and write it to the text file 'Smoke_004 DD-MM-yyyy HH-mm.txt'
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("Smoke_004 " + dateFormat.format(date) + ".txt"), "utf-8"));
writer.write("Operating System : " + Login.driver.findElement
(By.xpath("html/body/div[4]/div/div[4]/div[2]/div[4]/div/div[1]/div[1]/table[1]/tbody/tr[2]/td[2]"))
.getText());
} catch (IOException ex) {
// report
} finally {
try {
writer.close();
} catch (Exception ex) {
}
}
Thanks for your input #Mardoz and #ErstwhileIII
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.
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.
I have this piece of code, just to try to write it to a file. But when I compile it, it doesn't display any errors, but text in my file is unreadable, some Unicode codes etc... I use eclipse IDE. What could be the reason for this?
public static void main(String[] args) {
String s = "Hello world!";
int i = 143141141;
try
{
//create new file with an ObjectOutputStream
FileOutputStream out = new FileOutputStream("test.txt");
ObjectOutputStream oout = new ObjectOutputStream(out);
//write something in a file
oout.writeObject(s);
oout.writeObject(i);
//close the stream
oout.close();
//create an ObjectInputStream for the file we created before
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream("test.txt"));
//read and print what we wrote before
System.out.println("" + (String) ois.readObject());
System.out.println("" + ois.readObject());
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
Since you are using ObjectOutputStream and ObjectInputStream , it will write in Object code , which is not readable , and as well when u read from file , it will come up as an Object so again as an Object ,
Use BufferedReader or Writer to write String into file , which can be read
FileReader f=new FileReader(new File("test.txt"));
BufferedReader f1=new BufferedReader(f)
;
With an ObjectOutputStream, you're using Serialization to write your objects to a file. Serialization is using an encoding system, and you use correctly an ObjectInputStream in your program to decode these objects. But you won't be able to read the information in the file created by the Serialization process.
You should use PrintWriter to write text files, ObjectOutputStream writes binary data.
Java ObjectOuputStream writes objects in a binary non human readable format which can be read only with ObjectInputStream.
Your code is working fine for me. If I understand it correctly when look at the contents of file by opening it in editor (say notepad or eclipse) you see characters stored as binary content in it. As you are using ObjectInputStream and ObjectOutputStream the behavior is correct.
You are not writing values of your String and Integer objects but their object representations in binary format. That is called object-serialization. That is some how encoded to represent all the information associate with the object not only its value That is only displayed when decoded in the same way as we encoded them. So, normal text editor cannot display the information as you expected.
If you want to save the string representation only, use the classes such as PrintWriter.
I tried your code. It's working perfectly for me. See the attached image.
Try cleaning your workspace. If it doesn't work, try creating a new Java project and copy the same code posted here and try. It should work.
You're making the folly of writing the output string through an ObjectOutputStream which serializes the String and Integer objects in your code and saves the Object state along with the value of the object. This is the reason why you see encoded text when you open the file. The following excerpt sums up the values which are stored when an Object is serialized:
The default serialization mechanism for an object writes the class of the object, the class signature, and the values of all non-transient and non-static fields. References to other objects (except in transient or static fields) cause those objects to be written also. Multiple references to a single object are encoded using a reference sharing mechanism so that graphs of objects can be restored to the same shape as when the original was written.(ObjectOutputStream)
The writeObject method is responsible for writing the state of the object for its particular class so that the corresponding readObject method can restore it.
Primitive data, excluding serializable fields and externalizable data, is written to the ObjectOutputStream in block-data records. A block data record is composed of a header and data. The block data header consists of a marker and the number of bytes to follow the header. (ObjectOutputStream javadoc)
The possible problem with your code is you are not flushing the output data. So that it might not get written to the output file.
Try the below code.
public static void main(String[] args) {
String s = "Hello world!";
int i = 143141141;
try
{
//create new file with an ObjectOutputStream
FileOutputStream out = new FileOutputStream("test.txt");
ObjectOutputStream oout = new ObjectOutputStream(out);
//write something in a file
oout.writeObject(s);
oout.flush();
oout.writeObject(i);
oout.flush();
//close the stream
out.close();
oout.close();
//create an ObjectInputStream for the file we created before
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.txt"));
//read and print what we wrote before
System.out.println("" + (String) ois.readObject());
System.out.println("" + ois.readObject());
ois.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
And also if you want to read your written objects into the file then you can't because they are written as serialized objects. For textual operation with files you can consider BufferedReader or PrintWriter. see the following code.
public class WriteToFileExample {
public static void main(String[] args) {
try {
String content = "This is the content to write into file";
File file = new File("c:\\desktop\\filename.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
After this you can open your text file and can see the written content in the human readable form and it is good practice to not to give "txt" formats when you are writing objects to the file. It's misleading.
Hope this helps.