英文:
Increment number every time program runs
问题
我想在每次运行我的程序时递增计数。我尝试运行下面的代码,但每次运行程序时它都只打印1。另外,是否有任何特殊操作需要执行以增加日期。
public class CounterTest {
int count = 0;
public static void main(String[] args) {
CounterTest test1 = new CounterTest();
test1.doMethod();
}
public void doMethod() {
count++;
System.out.println(count);
}
}
英文:
I want to increment the count every time my program runs. I tried running below code but it keeps on printing 1 every time i run the program. Also anything special i need to do to increase the date.
public class CounterTest {
int count = 0;
public static void main(String[] args) {
CounterTest test1 = new CounterTest();
test1.doMethod();
}
public void doMethod() {
count++;
System.out.println(count);
}
}
答案1
得分: 2
你可以为你的应用程序简单地创建一个属性文件,用来追踪这类事物和应用程序的配置细节。当然,这个文件将是一个包含属性名称(键)及其相应值的简单文本文件。
以下是两个小方法可以帮助你开始:
setProperty() 方法:
使用这个方法,你可以创建一个属性文件,并应用任何你喜欢的属性名称和值。如果文件不存在,它会在指定的文件路径自动创建:
public static boolean setProperty(String propertiesFilePath,
String propertyName, String value) {
java.util.Properties prop = new java.util.Properties();
if (new java.io.File(propertiesFilePath).exists()) {
try (java.io.FileInputStream in = new java.io.FileInputStream(propertiesFilePath)) {
prop.load(in);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); }
catch (java.io.IOException ex) { System.err.println(ex); }
}
try (java.io.FileOutputStream outputStream = new java.io.FileOutputStream(propertiesFilePath)) {
prop.setProperty(propertyName, value);
prop.store(outputStream, null);
outputStream.close();
return true;
}
catch (java.io.FileNotFoundException ex) {
System.err.println(ex);
}
catch (java.io.IOException ex) {
System.err.println(ex);
}
return false;
}
如果你还没有特定的属性文件,那么在应用程序启动时(可能是初始化之后)调用上述方法是个好主意,这样你就可以有默认值可供使用,例如:
if (!new File("config.properties").exists()) {
setProperty("config.properties", "ApplicationRunCount", "0");
}
上面的代码会检查是否已经存在名为 config.properties 的属性文件(你应该总是使用 .properties
文件扩展名)。如果不存在,它会创建该文件,并将属性名(键)以及提供的值应用到其中。在上面的示例中,我们正在创建 ApplicationRunCount 属性,这基本上是为你的特定需求而设的。当你查看创建的 config.properties 文件时,会看到:
#Mon Sep 28 19:07:08 PDT 2020
ApplicationRunCount=0
getProperty() 方法:
这个方法可以从特定的属性名称(键)中检索值。每当你需要从属性文件中获取特定属性的值时,可以使用这个方法:
public static String getProperty(String propertiesFilePath, String key) {
try (java.io.InputStream ips = new java.io.FileInputStream(propertiesFilePath)) {
java.util.Properties prop = new java.util.Properties();
prop.load(ips);
return prop.getProperty(key);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); }
catch (java.io.IOException ex) { System.err.println(ex); }
return null;
}
你的任务:
让人困惑的是,你说你想要追踪你的 程序 运行的次数,但你在名为 doMethod() 的方法中递增了名为 count 的计数变量。如果你可以保证这个方法在整个应用程序运行期间只运行一次,那么这将起作用。如果不是这种情况,你可能会得到一个不真实地表示应用程序启动次数的计数总数。
无论如何,根据你目前使用的方案,你可以这样做:
public class CounterTest {
// 类构造函数
public CounterTest() {
/* 如果 config.properties 文件不存在,
则创建它并应用 ApplicationRunCount
属性,值为 0。 */
if (!new java.io.File("config.properties").exists()) {
setProperty("config.properties", "ApplicationRunCount", "0");
}
}
public static void main(String[] args) {
new CounterTest().doMethod(args);
}
private void doMethod(String[] args) {
int count = Integer.valueOf(getProperty("config.properties",
"ApplicationRunCount"));
count++;
setProperty("config.properties", "ApplicationRunCount",
String.valueOf(count));
System.out.println(count);
}
public static String getProperty(String propertiesFilePath, String key) {
try (java.io.InputStream ips = new
java.io.FileInputStream(propertiesFilePath)) {
java.util.Properties prop = new java.util.Properties();
prop.load(ips);
return prop.getProperty(key);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); }
catch (java.io.IOException ex) { System.err.println(ex); }
return null;
}
public static boolean setProperty(String propertiesFilePath,
String propertyName, String value) {
java.util.Properties prop = new java.util.Properties();
if (new java.io.File(propertiesFilePath).exists()) {
try (java.io.FileInputStream in = new java.io.FileInputStream(propertiesFilePath)) {
prop.load(in);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); }
catch (java.io.IOException ex) { System.err.println(ex); }
}
try (java.io.FileOutputStream outputStream = new java.io.FileOutputStream(propertiesFilePath)) {
prop.setProperty(propertyName, value);
prop.store(outputStream, null);
return true;
}
catch (java.io.FileNotFoundException ex) {
System.err.println(ex);
}
catch (java.io.IOException ex) {
System.err.println(ex);
}
return false;
}
}
每当你启动应用程序时,你将在控制台窗口中看到运行计数。其他有用的方法可能是 removeProperty() 和 renameProperty()。以下是它们:
/**
* 从提供的属性文件中删除指定的属性名。<br>
*
* @param propertiesFilePath(String)要从中删除属性名的属性文件的完整路径和文件名。<br>
*
* @param propertyName(String)要从属性文件中删除的属性名。<br>
*
* @return(布尔值)如果成功则返回 true,否则返回 false。
*/
public static boolean removeProperty(String propertiesFilePath,
String propertyName) {
java.util.Properties prop = new java.util.Properties();
if (new java.io.File(propertiesFilePath).exists()) {
try (java.io.FileInputStream in = new java.io.FileInputStream(propertiesFilePath)) {
prop.load(in);
prop.remove(propertyName);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); return false; }
catch (java.io.IOException ex) { System.err.println(ex); return false; }
}
try (java.io.FileOutputStream out = new java.io.FileOutputStream(properties
<details>
<summary>英文:</summary>
You could simply create a properties file for your application to keep track of such things and application configuration details. This of course would be a simple text file containing property names (keys) and their respective values.
Two small methods can get you going:
> **The *setProperty()* Method:**
With is method you can create a properties file and apply whatever property names and values you like. If the file doesn't already exist then it is automatically created at the file path specified:
public static boolean setProperty(String propertiesFilePath,
String propertyName, String value) {
java.util.Properties prop = new java.util.Properties();
if (new java.io.File(propertiesFilePath).exists()) {
try (java.io.FileInputStream in = new java.io.FileInputStream(propertiesFilePath)) {
prop.load(in);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); }
catch (java.io.IOException ex) { System.err.println(ex); }
}
try (java.io.FileOutputStream outputStream = new java.io.FileOutputStream(propertiesFilePath)) {
prop.setProperty(propertyName, value);
prop.store(outputStream, null);
outputStream.close();
return true;
}
catch (java.io.FileNotFoundException ex) {
System.err.println(ex);
}
catch (java.io.IOException ex) {
System.err.println(ex);
}
return false;
}
If you don't already contain a specific properties file then it would be a good idea to call the above method as soon as the application starts (perhaps after initialization) so that you have default values to play with if desired, for example:
if (!new File("config.properties").exists()) {
setProperty("config.properties", "ApplicationRunCount", "0");
}
The above code checks to see if the properties file named **config.properties** already exists (you should always use the `.properties` file name extension). If it doesn't then it is created and the property name (Key) is applied to it along with the supplied value for that property. Above we are creating the **ApplicationRunCount** property which is basically for your specific needs. When you look into the **config.properties** file created you will see:
#Mon Sep 28 19:07:08 PDT 2020
ApplicationRunCount=0
> **The *getProperty()* Method:**
This method can retrieve a value from a specific property name (key). Whenever you need the value from a particular property contained within your properties file then this method can be used:
public static String getProperty(String propertiesFilePath, String key) {
try (java.io.InputStream ips = new java.io.FileInputStream(propertiesFilePath)) {
java.util.Properties prop = new java.util.Properties();
prop.load(ips);
return prop.getProperty(key);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); }
catch (java.io.IOException ex) { System.err.println(ex); }
return null;
}
> **Your Task:**
What is confusing here is you say you want to keep track of the number of times your **Program** is run yet you increment your counter variable named **count** within a method named **doMethod()**. This would work if you can guarantee that this method will only run once during the entire time your application runs. If this will indeed be the case then you're okay. If it isn't then you would possibly get a count total that doesn't truly represent the actual number of times your application was started.
In any case, with the scheme you're currently using, you could do this:
public class CounterTest {
// Class Constructor
public CounterTest() {
/* If the config.properties file does not exist
then create it and apply the ApplicationRunCount
property with the value of 0. */
if (!new java.io.File("config.properties").exists()) {
setProperty("config.properties", "ApplicationRunCount", "0");
}
}
public static void main(String[] args) {
new CounterTest().doMethod(args);
}
private void doMethod(String[] args) {
int count = Integer.valueOf(getProperty("config.properties",
"ApplicationRunCount"));
count++;
setProperty("config.properties", "ApplicationRunCount",
String.valueOf(count));
System.out.println(count);
}
public static String getProperty(String propertiesFilePath, String key) {
try (java.io.InputStream ips = new
java.io.FileInputStream(propertiesFilePath)) {
java.util.Properties prop = new java.util.Properties();
prop.load(ips);
return prop.getProperty(key);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); }
catch (java.io.IOException ex) { System.err.println(ex); }
return null;
}
public static boolean setProperty(String propertiesFilePath,
String propertyName, String value) {
java.util.Properties prop = new java.util.Properties();
if (new java.io.File(propertiesFilePath).exists()) {
try (java.io.FileInputStream in = new java.io.FileInputStream(propertiesFilePath)) {
prop.load(in);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); }
catch (java.io.IOException ex) { System.err.println(ex); }
}
try (java.io.FileOutputStream outputStream = new java.io.FileOutputStream(propertiesFilePath)) {
prop.setProperty(propertyName, value);
prop.store(outputStream, null);
return true;
}
catch (java.io.FileNotFoundException ex) {
System.err.println(ex);
}
catch (java.io.IOException ex) {
System.err.println(ex);
}
return false;
}
}
Whenever you start your application you will see the run count within the Console Window. Other useful methods might be **removeProperty()** and **renameProperty()**. Here they are:
/**
* Removes (deletes) the supplied property name from the supplied property
* file.<br>
*
* @param propertiesFilePath (String) The full path and file name of the
* properties file you want to remove a property name from.<br>
*
* @param propertyName (String) The property name you want to remove from
* the properties file.<br>
*
* @return (Boolean) Returns true if successful and false if not.
*/
public static boolean removeProperty(String propertiesFilePath,
String propertyName) {
java.util.Properties prop = new java.util.Properties();
if (new java.io.File(propertiesFilePath).exists()) {
try (java.io.FileInputStream in = new java.io.FileInputStream(propertiesFilePath)) {
prop.load(in);
prop.remove(propertyName);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); return false; }
catch (java.io.IOException ex) { System.err.println(ex); return false; }
}
try (java.io.FileOutputStream out = new java.io.FileOutputStream(propertiesFilePath)) {
prop.store(out, null);
return true;
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); }
catch (java.io.IOException ex) { System.err.println(ex); }
return false;
}
/**
* Renames the supplied property name within the supplied property file.<br>
*
* @param propertiesFilePath (String) The full path and file name of the
* properties file you want to rename a property in.<br>
*
* @param oldPropertyName (String) The current name of the property you want
* to rename.<br>
*
* @param newPropertyName (String) The new property name you want to use.<br>
*
* @return (Boolean) Returns true if successful and false if not.
*/
public static boolean renameProperty(String propertiesFilePath, String oldPropertyName,
String newPropertyName) {
String propertyValue = getProperty(propertiesFilePath, oldPropertyName);
if (propertyValue == null) { return false; }
java.util.Properties prop = new java.util.Properties();
if (new java.io.File(propertiesFilePath).exists()) {
try (java.io.FileInputStream in = new java.io.FileInputStream(propertiesFilePath)) {
prop.load(in);
prop.remove(oldPropertyName);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); return false; }
catch (java.io.IOException ex) { System.err.println(ex); return false ;}
}
try (java.io.FileOutputStream out = new java.io.FileOutputStream(propertiesFilePath)) {
prop.store(out, null);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); return false; }
catch (java.io.IOException ex) { System.err.println(ex); return false; }
return setProperty(propertiesFilePath, newPropertyName, propertyValue);
}
</details>
# 答案2
**得分**: 1
请尝试这个。
```java
public class CounterTest {
static final Path path = Path.of("counter.txt");
int count;
CounterTest() throws IOException {
try {
count = Integer.valueOf(Files.readString(path));
} catch (NoSuchFileException | NumberFormatException e) {
count = 0;
}
}
public void doMethod() throws IOException {
++count;
System.out.println(count);
Files.writeString(path, "" + count);
}
public static void main(String[] args) throws IOException {
CounterTest c = new CounterTest();
c.doMethod();
}
}
英文:
Try this.
public class CounterTest {
static final Path path = Path.of("counter.txt");
int count;
CounterTest() throws IOException {
try {
count = Integer.valueOf(Files.readString(path));
} catch (NoSuchFileException | NumberFormatException e) {
count = 0;
}
}
public void doMethod() throws IOException {
++count;
System.out.println(count);
Files.writeString(path, "" + count);
}
public static void main(String[] args) throws IOException {
CounterTest c = new CounterTest();
c.doMethod();
}
}
答案3
得分: 0
以下是翻译好的部分:
你无法唯一的方法是使用数据库,或者更简单地使用txt文件来保存数字,每次运行应用程序时都读取txt文件并获取数字。
以下是如何实现的:
这是主类:
package main;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
String path = "C:\\Example.txt";
int number = 0;
try {
ReadFile file = new ReadFile(path);
String[] aryLines = file.OpenFile();
try {
number = Integer.parseInt(aryLines[0]);
} catch (Exception e) {
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
System.out.println(number);
number++;
File txtfile = new File(path);
if (txtfile.exists()) {
txtfile.delete();
try {
txtfile.createNewFile();
WriteFile data = new WriteFile(path, true);
data.writeToFile(number + "");
} catch (IOException ex) {
}
} else {
try {
System.out.println("no yei");
txtfile.createNewFile();
WriteFile data = new WriteFile(path, true);
data.writeToFile(number + "");
} catch (IOException ex) {
}
}
}
}
写入所需内容的类:
package main;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;
public class WriteFile {
public String path;
public boolean append_to_file = false;
public WriteFile(String file_path) {
path = file_path;
}
public WriteFile(String file_path, boolean append_value) {
path = file_path;
append_to_file = append_value;
}
public void writeToFile(String textline) throws IOException {
FileWriter write = new FileWriter(path, append_to_file);
PrintWriter print_line = new PrintWriter(write);
print_line.printf("%s" + "%n", textline);
print_line.close();
}
}
获取文件中文本内容的类:
package main;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ReadFile {
private static String path;
public ReadFile(String file_path){
path = file_path;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
for (int j = 0; j < numberOfLines; j++) {
textData[j] = textReader.readLine();
}
textReader.close();
return textData;
}
static int readLines() throws IOException {
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
String aLine;
int numberOfLines = 0;
while((aLine = bf.readLine()) != null){
numberOfLines++;
}
bf.close();
return numberOfLines;
}
}
英文:
You can't the only way is to use a Database or simpler use a txt file to save the number and every time you run your app reads the txt file and gets the number.
Here is How to do it:
This is the Main class:
package main;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
String path = "C:\\Example.txt";
int number = 0;
try {
ReadFile file = new ReadFile(path);
String[] aryLines = file.OpenFile();
try {
number = Integer.parseInt(aryLines[0]);
} catch (Exception e) {
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
System.out.println(number);
number++;
File txtfile = new File(path);
if (txtfile.exists()) {
txtfile.delete();
try {
txtfile.createNewFile();
WriteFile data = new WriteFile(path, true);
data.writeToFile(number + "");
} catch (IOException ex) {
}
} else {
try {
System.out.println("no yei");
txtfile.createNewFile();
WriteFile data = new WriteFile(path, true);
data.writeToFile(number + "");
} catch (IOException ex) {
}
}
}
}
the class that writes anything you need:
package main;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;
public class WriteFile {
public String path;
public boolean append_to_file = false;
public WriteFile(String file_path) {
path = file_path;
}
public WriteFile(String file_path, boolean append_value) {
path = file_path;
append_to_file = append_value;
}
public void writeToFile(String textline) throws IOException {
FileWriter write = new FileWriter(path, append_to_file);
PrintWriter print_line = new PrintWriter(write);
print_line.printf("%s" + "%n", textline);
print_line.close();
}
}
And this one is the one that gets the text on the file:
package main;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ReadFile {
private static String path;
public ReadFile(String file_path){
path = file_path;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
for (int j = 0; j < numberOfLines; j++) {
textData[j] = textReader.readLine();
}
textReader.close();
return textData;
}
static int readLines() throws IOException {
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
String aLine;
int numberOfLines = 0;
while((aLine = bf.readLine()) != null){
numberOfLines++;
}
bf.close();
return numberOfLines;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论