Java Properties store() 方法



描述

Java Properties store(OutputStream out,String comments) 方法将此属性列表(键值对)以适合使用 load(InputStream) 方法加载到 Properties 表格的格式写入此 Properties 表格中的输出流。

声明

以下是 java.util.Properties.store() 方法的声明

public void store(OutputStream out,String comments)

参数

  • out − 输出流。

  • comments − 属性列表的描述。

返回值

此方法返回此属性列表中指定键的前一个值,如果它没有键,则返回 null。

异常

  • IOException − 如果将此属性列表写入指定的输出流引发 IOException。

  • ClassCastException − 如果此 Properties 对象包含任何不是字符串的键或值。

  • NullPointerException − 如果 out 为 null。

Java Properties store(Writer writer,String comments) 方法

描述

java Properties store(Writer writer,String comments) 方法将此属性列表(键值对)以适合使用 load(Reader) 方法的格式写入此 Properties 表格中的输出字符流。

声明

以下是 java.util.Properties.store() 方法的声明

public void store(Writer writer,String comments)

参数

  • out − 输出字符流写入器。

  • comments − 属性列表的描述。

返回值

此方法返回此属性列表中指定键的前一个值,如果它没有键,则返回 null。

异常

  • IOException − 如果将此属性列表写入指定的输出流引发 IOException。

  • ClassCastException − 如果此 Properties 对象包含任何不是字符串的键或值。

  • NullPointerException − 如果 out 为 null。

将属性条目存储到控制台示例

以下示例显示了 Java Properties store(OutputStream, String) 方法的使用方法。我们创建了一个 Properties 对象。然后添加了一些属性并打印出来。然后我们将属性存储到 System.out 以在控制台上打印。

package com.tutorialspoint;

import java.io.IOException;
import java.util.Properties;

public class PropertiesDemo {
   public static void main(String[] args) {
      Properties prop = new Properties();

      // add some properties
      prop.setProperty("Height", "200");
      prop.put("Width", "1500");

      // print the list 
      System.out.println("" + prop);
      
      try {
         // store the properties list in an output stream
         prop.store(System.out, "PropertiesDemo");
      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

{Height=200, Width=1500}
#PropertiesDemo
#Mon Dec 26 13:17:45 IST 2022
Height=200
Width=1500

将属性条目存储到字符串示例

以下示例显示了 Java Properties store(OutputStream, String) 方法的使用方法。我们创建了一个 Properties 对象。然后添加了一些属性并打印出来。然后我们将属性存储到 System.out 以在控制台上打印。

package com.tutorialspoint;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Properties;

public class PropertiesDemo {
   public static void main(String[] args) {
      Properties prop = new Properties();
      StringWriter sw = new StringWriter();

      // add some properties
      prop.setProperty("Height", "200");
      prop.put("Width", "1500");

      // print the list 
      System.out.println("" + prop);
      
      try {
      
         // store the properties list in an output writer
         prop.store(sw, "PropertiesDemo");

         // print the writer
         System.out.println("" + sw.toString());
      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

{Height=200, Width=1500}
#PropertiesDemo
#Mon Dec 26 13:19:47 IST 2022
Height=200
Width=1500
java_util_properties.htm
广告

© . All rights reserved.