Java writing to a file [duplicate] - java

This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 9 years ago.
I have a problem with writing to file in Java. I want to write to .txt file but when program writes anything , it deletes before written. I don't want it. I used flw.write before using flw.append but nothing change. Can you help me ?
public void list(String path) throws IOException {
FileWriter flw=new FileWriter(path);
flw.append("----------------------------------------------List---------------------------------------------\n");
for (int i = 0; i < athCtr - 1; i++) {
flw.append("Author:" + athr[i].getId() + "\t"
+ athr[i].getName() + "\t" + athr[i].getUniv() + "\t"
+ athr[i].getDepart() + "\t" + athr[i].getEmail()+"\n");
if (athr[i].getArtCtr() != 0) {
for (int j = 0; j < athr[i].getArtCtr(); j++) {
flw.append("+" + athr[i].getArticle(j) + ":");
for (int k = 0; k < artCtr; k++) {
if (art[k].getPaperId().equals(athr[i].getArticle(j))) {
flw.append("\t" + art[k].getName() + "\t"
+ art[k].getPublisherName() + "\t"
+ art[k].getPublishYear()+"\n");
}
}
}
flw.append("\n");
}
}
flw.append("Author:" + athr[athCtr - 1].getId() + "\t"
+ athr[athCtr - 1].getName() + "\t"
+ athr[athCtr - 1].getUniv() + "\t"
+ athr[athCtr - 1].getDepart() + "\t"
+ athr[athCtr - 1].getEmail()+"\n");
if (athr[athCtr - 1].getArtCtr() != 0) {
for (int j = 0; j < athr[athCtr - 1].getArtCtr(); j++) {
flw.append("+" + athr[athCtr - 1].getArticle(j) + ":");
for (int k = 0; k < artCtr; k++) {
if (art[k].getPaperId().equals(
athr[athCtr - 1].getArticle(j))) {
flw.append("\t" + art[k].getName() + "\t"
+ art[k].getPublisherName() + "\t"
+ art[k].getPublishYear()+"\n");
}
}
}
}
flw.append("----------------------------------------------End----------------------------------------------\n\n");
flw.close();
}

This question should probably be closed as it has been asked and answered many many times, but the key is to use the correct FileWriter constructor, one that takes true as a second parameter. The second true parameter tells Java to open the file for appending rather than overwriting.
//FileWriter flw = new FileWriter(path); // not this
FileWriter flw = new FileWriter(path, true); // but this
And in fact, I am voting to close this question as a duplicate.
As an aside: you'll probably not want to write directly with the FileWriter but rather will want to wrap it in a BufferedWriter or (my preference) a PrintWriter instance. This will allow you to simply and more efficiently write to the file using println(...) and other familiar methods.
Edit 2: After looking more at your code, I think that actually you should consider using a PrintWriter class and then writing with the printf(...) method as this allows for formatted String output, something that works much better than a bunch of tabs as you're trying to do.

Related

get untitled column data from CSV file [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
I have this code, which supposed to retrieve data from CSV file, the file (set of files) structure is as following: [Mary, 7, 17] but the columns are not titled, so I only got A, B, C
when I run the code I seem to have only the first result in the column.
can anybody help me to iterate throw all records?
public void searchFiles()
{
int count = 0;
DirectoryResource c = new DirectoryResource();
int summ = 0;
int currentrow = 0;
String name = "ff";
String k = "Susan";
for(File f : c.selectedFiles())
{
FileResource fr = new FileResource(f);
CSVParser currentFile = fr.getCSVParser(false);
currentrow = 0;
for (CSVRecord row : currentFile)
{
currentrow++;
name = row.get(0);
if(row.get(0) == k)
{
count++;
summ = summ + currentrow;
System.out.println("Row is : " + row.getRecordNumber() + " / " + currentrow);
break;
}
else
{
System.out.println("found");
}
}
System.out.println(count + " / " + currentrow + " / " + name);
}
System.out.println("count is: " + count);
System.out.println("Summ is: " + summ);
System.out.println("Avg is: " + (summ / count));
}
I should use .equals() insted of == in the if statement
if(row.get(0).equals(k))

How to arrange and rename files according to number?

I want to arrange files first and rename them according to their order that is specified by a number in the file name.
For example:
I have a folder that contains a bunch of different files. The file names are indicated by a number at the end of it. Let's say we have the following files in that folder:
file_1.xml // Remains unchanged
file_2.xml // Remains unchanged
file_4.xml // Should be renamed to "file_3.xml"
file_9.xml // Should be renamed to "file_4.xml"
file_12.xml // Should be renamed to "file_5.xml"
How do I do that? I want to create a reliable clean method that renames files in order.
So far:
private void updateFilesName() {
for (int i = 1; i <= filesAmount; i++) {
File file1 = new File(getFilesDir().getParent() + "/file_" + i + ".xml");
File file2 = new File(getFilesDir().getParent() + "/file_" + String.valueOf(i + 1) + ".xml");
if (!file1.exists() && file2.exists()) {
file2.renameTo(file1);
}
}
}
But that only works if the difference between 2 file positions was 1. (like between file_2 and file_4) This method won't work for file_9 and file_12.
private void updateFilesName() {
int j;
for (int i = 1; i <= filesAmount; i++) {
File file1 = new File(getFilesDir().getParent() + "/file_" + i + ".xml");
if (!file1.exists()) {
j = i+1;
while (!(new File(getFilesDir().getParent() + "/file_" + j + ".xml")).exists()) {
j++;
}
(new File(getFilesDir().getParent() + "/file_" + j + ".xml")).renameTo(file1);
}
}
}
// Iterate all files under the directory and check the file name
File folder = new File("urdirectory");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
if (!listOfFiles[i].getName().equals("file_" + (i+1) + ".xml")) {
File tempFile1 = listOfFiles[i];
File tempFile2 = new File("urdirectory" + "/file_" + String.valueOf(i + 1) + ".xml");
tempFile.renameTo(tempFile2);
}
}

How to go down lines when trying to write to a file with Java [duplicate]

This question already has answers here:
File Writer overrides previous write Java
(2 answers)
Closed 7 years ago.
Using the code below, I am trying to make a log for a plugin, though, every time it makes a entry I want it to go below the other entry. Though, when I test it, it writes the second entry but the first entry gets deleted.
if (commandLabel.equalsIgnoreCase("logmeup")) {
entry++;
entry3 = entry * 3;
FileWriter fw= null;
File file =null;
try {
file = new File("playerLog.txt");
if(!file.exists()) {
file.createNewFile();
}
fw = new FileWriter(file);
if (entry == 1) {
fw.write("Name: " + player.getDisplayName() + "\nIP: " + player.getAddress() + "\nLocation: " + player.getLocation() + "\n");
fw.close();
}
else {
while (entryloop < entry3) {
entryloop++;
fw.write(System.getProperty( "line.separator" ));
}
entryloop = 0;
fw.write("Name: " + player.getDisplayName() + "\nIP: " + player.getAddress() + "\nLocation: " + player.getLocation() + "\n");
fw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Flaged as dupe yet I will answer it once again:
Pass second argument of FileWriter as true to make it go into append mode.
fw = new FileWriter(file,true);

How to highlight entire row if any cell is empty in html table

I have created html table in mail body using below code
st = con.createStatement();
rs = st.executeQuery("SELECT nvl(tt.ACTIVITY_NAME,'') as ACTIVITY_NAME, "
+ " nvl(tt.TL_NAME,'') TL_NAME, "
+ " nvl(tt.UW_NAME,'') UW_NAME, "
+ " nvl(tt.TAT_1,'') TAT_1,"
+ " nvl(tt.TAT_2,'') TAT_2, "
+ " nvl(tt.TAT_3,'') TAT_3, "
+ " nvl(tt.TAT_4,'') TAT_4, "
+ " nvl(tt.TAT_4_PLUS ,'') TAT_4_PLUS, "
+ " nvl(tt.g_total ,'') AS GRAND_TOTAL "
+ " FROM uw_activity_tl_uw_tat tt "
+ " WHERE tt.ACTIVITY_NAME = 'First UW' "
+ " ORDER BY tt.TL_NAME,tt.UW_NAME");
StringBuffer sb = new StringBuffer();
ResultSetMetaData rsmd = rs.getMetaData();
int numColumns = rsmd.getColumnCount();
for (int i = 1; i < numColumns + 1; i++) {
String columnName = rsmd.getColumnName(i);
sb.append("<th bgcolor=#fcbe07>" + columnName + "</th>");
}
ArrayList<String> a = new ArrayList<String>();
while (rs.next()) {
a.add(rs.getString(3));
if (rs.getRow() % 2 == 0) {
sb.append("<tr bgcolor=#fcf6cf>");
for (int i = 1; i < numColumns + 1; i++) {
if (rs.getString(i) == null) {
if(i==3)
{
sb.append("<td bgcolor=#fcbe07><b>"+ " "+ "</b></td>");
}
} else {
if (i == 6 || i == 7 || i == 8)
sb.append("<td><FONT COLOR=#ff0000>"
+ rs.getString(i) + "</FONT></td>");
else if(i==3 && (rs.getString(3).equalsIgnoreCase("") || rs.getString(3)==null)){
sb.append("<td bgcolor=#fcbe07><b>"+ rs.getString(i) + "</b></td>");
}else{
sb.append("<td>" + rs.getString(i) + "</td>");
}
}
}
sb.append("</tr>");
} else {
sb.append("<tr>");
for (int i = 1; i < numColumns + 1; i++) {
if (rs.getString(i) == null) {
if(i==3)
{
sb.append("<td bgcolor=#fcbe07><b>"+ " " + "</b></td>");
}
} else {
if (i == 6 || i == 7 || i == 8)
sb.append("<td><FONT COLOR=#ff0000>"
+ rs.getString(i) + "</FONT></td>");
else if(i==3 && (rs.getString(3).equalsIgnoreCase("") || rs.getString(3)==null)){
sb.append("<td bgcolor=#fcbe07><b>"+ rs.getString(i) + "</b></td>");
}else{
sb.append("<td>" + rs.getString(i) + "</td>");
}
}
}
sb.append("</tr>");
}
}
String html = "<html>" + message.getSubject()
+ "</title></head><body><table border=\"1\">"
+ sb.toString() + "</table></body></html>";
message.setContent(html, "text/html");
In the image only one cell is highlighted and I want to highlight the entire row which has any empty cell.Please guide. My query is how to highlight the entire row if any cell is empty.
Short answer: Move the check for the third column and change the <tr> line.
Truthfully, the code you have is a bit of a mess. Personally, I would make the following changes that will make maintence so much easier:
Switch to using classes instead of hard coding bgcolors and so forth.
Set up your system to return associative arrays instead of numeric arrays. That will make reading the code after a lot easier.
Set up intermediate variables to hold the values returned. Do any and all of your calculations and settings things there. THEN dump the entire table-row in one go. That separates your "functional" code from your "display code."
However, in a pinch, something like this will get you going:
tmp = rs.getString(3);
if (tmp == null) {
sb.append("<tr bgcolor=#ffffff>");
} else {
sb.append("<tr bgcolor=#fcf6cf>");
}
BTW - the HTML you generate isn't valid.
Of the top of my head
boolean cellNull = false;
while(rs.next()){
cellNull = false;
cellNull = checkIfAnyFieldIsNull(rs);
if(cellNull)
sb.append("<tr bgcolor=\"#WTH\">");
else
sb.append("<tr>");
//create rest of the row content here
}
private boolean checkIfAnyFieldIsNull(ResultSet rs){
for(i=0 etc..){
if(rs.getString(i) == null)
return true;
}
return false;
}
One way of doing it would be as follows:
Create a POJO class with all the columns that you want to display. Also have a boolean variable, say empty. Set it to true, if any of your column is null
Create a ArrayList and add each instance of your class as you iterate through your resultset
Now use this ArrayList to render your output. Since you already have the boolean variable availabe, you can use this value to set the background color of your row.

Google calendar indexoutofbounds when getTimes()

I'm trying to write a simple method, that gets events from Google calendar. The problem is that if i'm trying to call getTimes() on my events, i get an Indexoutofbounds exception.
I just can't figure out what the problem is.
Thanks in advance :)
jTextArea1.setText("");
try {
CalendarService myService = new CalendarService("myApp");
myService.setUserCredentials(username, password);
String eventTitle = "";
for (URL u : urls) {
CalendarQuery myQuery = new CalendarQuery(u);
myQuery.setMinimumStartTime(convertStartDateToDateTime());
myQuery.setMaximumStartTime(convertEndDateToDateTime());
myQuery.setFullTextQuery(searchTF.getText());
CalendarEventFeed resultFeed = myService.query(myQuery, CalendarEventFeed.class);
// System.out.println(resultFeed.getTitle().getPlainText());
for (int i = 0; i < resultFeed.getEntries().size(); i++) {
CalendarEventEntry entry = resultFeed.getEntries().get(i);
if (resultFeed.getEntries().size() > 0) {
jTextArea1.setText(jTextArea1.getText()
+ resultFeed.getTitle().getPlainText()
+ "\n");
eventTitle = resultFeed.getEntries().get(i).getTitle().getPlainText();
jTextArea1.setText(jTextArea1.getText() + eventTitle + "\n");
jTextArea1.setText(jTextArea1.getText()
+ "Start: " + resultFeed.getEntries().get(i).getTimes().get(i).getStartTime().toString() + "\n"
+ "Slut: " + resultFeed.getEntries().get(i).getTimes().get(i).getEndTime().toString() + "\n");
}
jTextArea1.setText(jTextArea1.getText() + "\n");
}
}
My guess is something is wrong with your second get(i),
resultFeed.getEntries().get(i).getTimes().get(i).getStartTime().toString()
While the first "i" in the get(i) is guaranteed to work because of i < resultFeed.getEntries().size(); condition in the for loop, the second "i" in the get(i) doesn't have any condition to check its range.
Kindly Post your full exception trace if this isn't your problem.

Categories