java 中从控制台输入两个数,并将相加的结果存入一个文本文件中
2个回答
2013-08-29
展开全部
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("请输入第一个数");
Scanner input = new Scanner(System.in);
int one = input.nextInt();
System.out.println("请输入第二个数");
int two=input.nextInt();
int sum=one+two;
System.out.println(one+"和"+two+"的和为:"+sum);
write("E:\\123.txt", String.valueOf(sum));
}
public static void write(String path, String content) {
String s = new String();
String s1 = new String();
try {
File f = new File(path);
if (f.exists()) {
System.out.println("文件存在");
} else {
System.out.println("文件不存在,正在创建...");
if (f.createNewFile()) {
System.out.println("文件创建成功!");
} else {
System.out.println("文件创建失败!");
}
}
BufferedReader input = new BufferedReader(new FileReader(f));
while ((s = input.readLine()) != null) {
s1 += s + "\n";
}
System.out.println("文件内容:" + s1);
input.close();
s1 += content;
BufferedWriter output = new BufferedWriter(new FileWriter(f));
output.write(s1);
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("请输入第一个数");
Scanner input = new Scanner(System.in);
int one = input.nextInt();
System.out.println("请输入第二个数");
int two=input.nextInt();
int sum=one+two;
System.out.println(one+"和"+two+"的和为:"+sum);
write("E:\\123.txt", String.valueOf(sum));
}
public static void write(String path, String content) {
String s = new String();
String s1 = new String();
try {
File f = new File(path);
if (f.exists()) {
System.out.println("文件存在");
} else {
System.out.println("文件不存在,正在创建...");
if (f.createNewFile()) {
System.out.println("文件创建成功!");
} else {
System.out.println("文件创建失败!");
}
}
BufferedReader input = new BufferedReader(new FileReader(f));
while ((s = input.readLine()) != null) {
s1 += s + "\n";
}
System.out.println("文件内容:" + s1);
input.close();
s1 += content;
BufferedWriter output = new BufferedWriter(new FileWriter(f));
output.write(s1);
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
2013-08-29
展开全部
这就是正确的答案?还没有明白你问的什么意思。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询