So I'm coding a program in Java that allows me to create teams (also remove them and edit them).
After creating a team the program enables the user to add 10 players, define their weight and tries scored and once again remove and edit them. Now as soon as they reach 10 players they lose the ability of adding more and a save button is enabled.
The problem I'm having is: if I save a team and then edit it or remove it and I try to save it again, the table creates another column and moves all the values one column to the right. The images will illustrate a bit better what I mean.
When saved for first time:
After saving 2nd time:
The code for the saving function is at follows:
private void btn_SaveTeamActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel pattern = (DefaultTableModel) table_PlayerBoard.getModel();
try {
saveTable((String) table_LeaderBoard.getValueAt(table_LeaderBoard.getRowCount() - 1, 0));
} catch (Exception ex) {
Logger.getLogger(Mainpage.class.getName()).log(Level.SEVERE, null, ex);
}
enableTeamEdit();
btn_SaveTeam.setEnabled(false);
JOptionPane.showMessageDialog(null, "Team Saved");
pattern.setRowCount(0);
btn_RankTeams.setEnabled(true);
counter = 0;
}
ArrayList <Integer> triesList = new ArrayList();
ArrayList <String> teamList = new ArrayList();
boolean check = false;
I can't really understand where is the mistake. If there is any more information needed let me know. Thanks in advance.
saveTable method:
public void saveTable(String fileName)throws Exception {
DefaultTableModel chart = (DefaultTableModel) table_PlayerBoard.getModel();
BufferedWriter bfw = new BufferedWriter(new FileWriter("C:\\Users\\" + System.getProperty("user.name") + "\\Desktop\\Sports\\" + fileName + ".txt"));
System.out.println(fileName);
for (int i = 0 ; i < chart.getRowCount(); i++)
{
for(int j = 0 ; j < chart.getColumnCount();j++)
{
bfw.write((chart.getValueAt(i,j).toString()));
bfw.write("\t");;
}
bfw.newLine();
}
bfw.close();
}
In your saveTable(...) method, simply delete the contents of the given file, then open a new one for writing like this:
String path = "C:\\Users\\" + System.getProperty("user.name") + "\\Desktop\\Sports\\" + fileName + ".txt";
File file = new File(path);
file.delete();
file = new File(path);
BufferedWriter bfw = new BufferedWriter(new FileWriter(file));
Related
I have a spring-boot application which is constantly writing JSON data to text file in a given location.
Now, I also want to create new text files dynamically, once the size limit is reached.
I was thinking of handling above things manually with code something like this
for (int i = 1; i < 1000; i++) {
try {
File f = new File(FILE_LOCATION + fileName);
fileSize = Files.size(f.toPath());
System.out.println("filesize: " + fileSize);
if (f.exists()) {
if (fileSize > SIZE_1KB) {
writer = new FileWriter(FILE_LOCATION + "00" + i + ".txt");
fileName = "00" + i + ".txt";
} else {
writer = new FileWriter(FILE_LOCATION + fileName, true);
}
} else {
writer = new FileWriter(FILE_LOCATION + fileName);
}
// use writer to write data
if (f.exists()) {
for (int j = 0; j < 10; j++)
writer.append(UUID.randomUUID().toString());
} else {
for (int j = 0; j < 10; j++)
writer.write(UUID.randomUUID().toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
This is just a piece of code that I created to post the question here.
But, the logic of writing data to file is similar to the one I was using in spring-boot application.
Also, if I want to handle things manually, I'll have to handle lot of things myself apart from creating new files when size limit is reached. Things like moving files to archived folder, when date if changed, deleting older files from archived folder when size limit of archived folder is reached, etc.
I've also looked into logback.xml configuration, but that's already being used for rolling out log files. So, I don't think I can use that here.
At this point, I feel like there might be a better way to do all this instead of handling it on our own manually. If anyone can suggest any library or framework or anything, it will be a great help.
Edit:
Okay, have come across rotating-fos. Trying to determine appropriate configuration, which can meet my general requirements of rotating based on size, date, deleting old records and when size limit reached.
Edit 2:
I've currently used rotating-fos library to achieve all the things mentioned above except deletion of files. Since, in my use case, text files are pushed to a data pipeline via separate procedure, which will again take care of removal of those files.
private void processEntry(Map<String, Object> entry) {
try {
String path = jsonProcessingPath + "/" + CALL_DATA + "/";
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
File dir = new File(path + format.format(new Date()));
if (!dir.exists())
dir.mkdir();
String fileName = CALL_DATA_FILE_NAME;
File file = new File(dir.getAbsolutePath() + "//" + fileName);
if (!file.exists())
file.createNewFile();
RotationConfig config = RotationConfig.builder().file(file.getAbsolutePath())
.filePattern(dir + "/" + CALL_DATA_FILE_NAME + ".%d{HHmmss}.txt")
.policy(new SizeBasedRotationPolicy(Long.parseLong(SIZE_LIMIT)))
.policy(DailyRotationPolicy.getInstance()).build();
RotatingFileOutputStream outputStream = new RotatingFileOutputStream(config);
Gson gson = new Gson();
String json = gson.toJson(entry);
int currentId = gson.fromJson(json, JsonObject.class).get(ID).getAsInt();
log.debug("Writing entry of report_data_calls table");
outputStream.write(json.getBytes());
outputStream.close();
exampleSchedulerService.updateJobDataMapInfo(ProcessCallDataJob.class, CALL_DATA_LAST_ID, currentId);
log.debug("Updated last processed call id to be: " + currentId);
} catch (Exception e) {
log.error("error: {}", e);
}
}
I think rotating-fos could be a good solution.
Anyway if you want to do it manually you can improve your code by combining two classes (Logger and FileHandler) from the java.util.logging package.
I wrote a little PoC, try to play around with it if you think that can be helpful.
public static void main(String[] args) throws IOException {
FileHandler fileHandler = new FileHandler("the_log.json", 100, 100, true);
fileHandler.setFormatter(new Formatter() {
#Override
public String format(LogRecord record) {
// here you could pretty print the content or doing elaborations on the content...
return record.getMessage();
}
});
Logger jsonLogger = Logger.getLogger("MyJsonLogger");
jsonLogger.setLevel(Level.ALL);
jsonLogger.addHandler(fileHandler);
for (int i = 0; i < 999; i++) {
jsonLogger.log(Level.ALL, i + "\n");
}
}
Please note that the FileHandler input parameters are a little bit tricky, here's the docs.
JSON files should be in UTF-8 encoding. FileWriter is a convenience class using the default operating system encoding. So non-portable.
For UUIDs (ASCII) that would function, but it is a ticking time bomb.
Just appending UUIDs misses spacing or such.
writer.append(UUID.randomUUID().toString()).append("\r\n");
You can use a logger for rolling file appenders. The hander can be tied to your class, so there is no interference.
I need help regarding my java GUI, I have a jform to add movie details into a textfile add movie into textfile
when I add the data and click the save button it will automatically print on the textfile file that has been declared inside the code.
now I am creating another jform to display a specific data that has inside the textfile into a jtextfield. However, I can't seem to have any idea on how to do it. can anyone guide me through this?
display textfile into jtextfield
This is my code to display the added movie into the jtable
float subPrice,totalPrice,tax;
int stockqty = Integer.parseInt(stock.getText());
float priceUnit = Float.parseFloat(unitP.getText());
subPrice = priceUnit*stockqty;
tax = (float) (subPrice*0.60);
totalPrice = subPrice+tax;
MovieInventory.AddRowToJTable(new Object[]{
movieID.getText(),
movieName.getText(),
yearR.getText(),
language.getText(),
genre.getSelectedItem(),
rated.getSelectedItem(),
duration.getText(),
type.getSelectedItem(),
stock.getText(),
unitP.getText(),
subPrice,
totalPrice,
});
JOptionPane.showMessageDialog(this, "Movie Add Succesfully!");
}
For the save button this is my code to save the data that has been put inside jtable into the textfile.
String filePath = "/Users/finatasha/Documents/inventoryMovie.txt";
File file = new File(filePath);
try {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for(int i = 0; i <jTable1.getRowCount(); i++){
for(int j=0; j< jTable1.getColumnCount(); j++){
bw.write(jTable1.getValueAt(i, j).toString()+" ,");
//using comma to seperate data
}
bw.newLine();
}
bw.close();
fw.close();
JOptionPane.showMessageDialog(this, "Data save to textfile successfully!");
} catch (IOException ex) {
Logger.getLogger(MovieInventory.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(this, "ERROR!");
}
Im making a medical resource management system and i am using a text file to import the first set of Doctors. This is working fine and i have added the ability to remove a selected row, which is also working. However i want this change to become permanent and save on the text.
When i press my save button on the Java GUI i just clears the entire text file. I also have the ability the add separate doctors which is also working correctly. Any help would be appreciated. Below is my code for exporting the Jtable to the text file!
private void jButtonSaveActionPerformed(java.awt.event.ActionEventevt)
{
String filePath = "C:\\Users\\Stephen\\folder\\Programming
Assignment copy\\doctor.txt";
File file = new File(filePath);
try {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for(int i = 0; i < jTableDoc.getRowCount(); i++){//rows
for(int j = 0; j < jTableDoc.getColumnCount(); j++){//columns
bw.write(jTableDoc.getValueAt(i, j).toString()+",");
}
bw.newLine();
}
bw.close();
fw.close();
} catch (IOException ex) {
Logger.getLogger(doctorTable.class.getName()).log(Level.SEVERE, null, ex);
} // TODO add your handling code here:
}
One class of my GUI has a variable for the file name. I want to pass this to another class so that I can process a file without having to hard code the file's name every time. The program compiles fine but I can't seem to run it correctly.
public void run() {
WordsCounter2 fileName = new WordsCounter2();
essayName = fileName.getFileList();
File f = new File(essayName);
//other code
WordsCounter2 is the class that houses the variable fileName, I'm calling it from this class and assigning it as the file's name, but this doesn't work. Could someone help?
if (rVal == JFileChooser.APPROVE_OPTION) {
File[] selectedFile = fileChooser.getSelectedFiles();
fileList = "nothing";
if (selectedFile.length > 0)
fileList = selectedFile[0].getName();
for (int i = 1; i < selectedFile.length; i++) {
fileList += ", " + selectedFile[i].getName();
}
statusBar.setText("You chose " + fileList);
}
else {
statusBar.setText("You didn't choose a file.");
}
fileList isn't empty because I have a label on the GUI that lists whatever file I chose.
Here's my new edit: now the exception occurs at the last line with the scanner and throws a NPE. Can you help?
public void run() {
WordsCounter2 pathNamesList = new WordsCounter2();
essayName = pathNamesList.getPathNamesList();
essayTitle = new String[essayName.size()];
essayTitle = essayName.toArray(essayTitle);
for (int i = 0; i < essayTitle.length; i++) {
f = new File(essayTitle[i]);
}
try {
Scanner scanner = new Scanner(f);
Your code is failing because File will not accept comma separated file names, in fact, it needs a single file path to create the file in the mentioned path. See here: https://docs.oracle.com/javase/7/docs/api/java/io/File.html
You'll have to get complete paths in an array and put the file creation statement as follows:
File f;
for (int i=0; i<fileList.length; i++)
f = new File(fileList[i]);
where fileList is a String array holding the list of pathnames.
In case you're trying to write some content to these files as well, this should be helpful: Trying to Write Multiple Files at Once - Java
I'm trying to code something to copy the content of one file into another existent file without deleting its content.
The problem is that, that other existent file is created inside a loop and I don't know how to do it to save it and then using it in another method.
Here's the loop:
if (line.startsWith("tipo1.")) {
FileWriter fw = new FileWriter(name + ".txt");
char[] vector = name.toCharArray();
char[] vector2 = address.toCharArray();
int index = 0;
while (index < vector.length) {
fw.write(vector[index]);
index++;
}
index = 0;
while (index < vector2.length) {
fw.write(vector2[index]);
index++;
}
fw.close();
}
And what I want to do is to save (name + ".txt") file and then adding the content of another file into it.
I'm sure it's not so difficult to do, but I'm really stuck.
You already have two separate pieces of information being written into the file: the name (as vector) and the address (as vector2). Why not just read in your other file as, say, vector3 and add one more while loop?
If you want this done the easy way then use Apache IO, and use: File ip = new File("input.txt"); File op = new File("output.txt"); FileUtils.copyFile(ip, op);
FileReader ip = new FileReader("input.txt");
FileWriter op = new FileWriter("output.txt", true);
int c;
while (true) {
c = ip.read();
if (c == -1) {
break;
}
op.write((char)c);
}
ip.close();
op.close();