Java中如何实现读取文件!需要注意的是,自已的工程下需要有一个"temp.properties"的文件,扩展名必须是".properties'此文件是用来存放读取文件的内容。
#File's title!
#Mon Apr 28 10:00:09 CST 2008
4=44
3=33
2=22
1=11
0=00
上段内容就是执行完以下Java代码后,"temp.properties"的文件里的内容。
以下代码就是实现如何读取文件,其工程结构如下图:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class ReadText {
/** JAVA Properties */
private static Properties properties = null;
/** Propertyファイルパス */
private final String path = "temp.properties";
/**
* メソッド名:Instants
* 機能概要:Propertiesファイルを読入する
*
* @param なし
* @return なし
* @throws なし
*/
public void Instants() {
if (properties == null) {
properties = new Properties();
try {
// Propertiesファイルを読入する
properties.load(new FileInputStream(path));
} catch (IOException e) {
System.err.println("ERROR: " + e);
}
}
}
/**
* メソッド名:getValue
* 機能概要:KEY値を取得する
*
* @param なし
* @return String Key
* @throws なし
*/
public String getValue(String key) {
return properties.getProperty(key);
}
/**
* メソッド名:setValue
* 機能概要:VALUE値を変更する
*
* @param KEY値
* key
* @param VALUE値
* value
* @return なし
* @throws なし
*/
public void setValue(String key, String value) {
properties.setProperty(key, value);
try {
// VALUE値を変更する
properties.store(new FileOutputStream(path), "File's title!");
} catch (FileNotFoundException e) {
System.err.println("ERROR: " + e);
} catch (IOException e) {
System.err.println("ERROR: " + e);
}
}
/** * メソッド名:getProperty
* 機能概要:Propertiesを取得する * @param なし * @return Property設定 strProperty * @throws なし */ public String[]getProperty(){ String []valuePro = new String[5]; for(int i =0;i<5;i++){ valuePro[i] = getValue(Integer.toString(i)); } return valuePro; } /** * メソッド名:setProperty
* 機能概要:Propertyを設定する * @param 時間間隔 setTime * @param プロジェクト名 groupName * @param ユーザー名 userName * @return なし * @throws なし */ public void setProperty(){ Instants(); for(int i=0;i<5;i++){ setValue(Integer.toString(i),Integer.toString(i)+Integer.toString(i)); } } public static void main(String[] args){ String [] tt = new String[3]; ReadText rt = new ReadText(); rt.setProperty(); tt = rt.getProperty(); for(int i=0;i<5;i++){ System.out.println(tt[i]); } }}