1个回答
展开全部
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.Scanner;
/**
* 用JAVA程序把一个int变量存到一个txt中,再取出来后赋给别一个int变量
*
* @author ajax_2003
* @version 1.0, 2009-7-26
*
*/
public class FileControlTest {
private static String FILE_PATH = "d:/abc.txt";
private static File file;
static {
file = new File(FILE_PATH);
}
/**
* 写入到文件
*
* @param str
*/
private void writeToFile(int num) {
FileWriter out = null;
try {
out = new FileWriter(file);
out.write(String.valueOf(num));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null)
out.close();
out = null;
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
/**
* 从文件中读取
*
* @return
*/
private int readFromFile() {
int result = -1;
try {
Scanner reader = new Scanner(file);
result = reader.nextInt();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
FileControlTest fct = new FileControlTest();
fct.writeToFile(5);
int n = fct.readFromFile();
System.out.println(n);
}
}
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.Scanner;
/**
* 用JAVA程序把一个int变量存到一个txt中,再取出来后赋给别一个int变量
*
* @author ajax_2003
* @version 1.0, 2009-7-26
*
*/
public class FileControlTest {
private static String FILE_PATH = "d:/abc.txt";
private static File file;
static {
file = new File(FILE_PATH);
}
/**
* 写入到文件
*
* @param str
*/
private void writeToFile(int num) {
FileWriter out = null;
try {
out = new FileWriter(file);
out.write(String.valueOf(num));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null)
out.close();
out = null;
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
/**
* 从文件中读取
*
* @return
*/
private int readFromFile() {
int result = -1;
try {
Scanner reader = new Scanner(file);
result = reader.nextInt();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
FileControlTest fct = new FileControlTest();
fct.writeToFile(5);
int n = fct.readFromFile();
System.out.println(n);
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询