java题,在线等,急!!!!!

如题所述

第1个回答  2015-04-22
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

public class Introduction {
//姓名
private String name;
//年龄
private int age;
//专业
private String major;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}

public Introduction(){}

/**
 * 自我介绍
 */
public String introduction(){
//自我介绍的内容
String str = "大家好!我叫"+name+",今年"+age+"岁,所学的专业是"+major+"。";
// System.out.println(str);
return str;
}

public String getDafaultPath(){
return "D:"+File.separator+"MyIntroduction"+File.separator+"jabc.temp";
}

public void writeInDevice(String str,String path){
//输出流
BufferedWriter write = null;
try {
//获取文件对象
File file = new File(path);
if(!file.getParentFile().exists())file.getParentFile().mkdirs();
//检查本地是否存在相同的文件,如果存在就替换掉。不存在的话就新创建一个。
if(!file.exists())file.createNewFile();
//以utf-8的编码格式创建输出流.并写入文件
FileOutputStream out = new FileOutputStream(file);
write = new BufferedWriter(new OutputStreamWriter(out,"utf-8"));
write.write(str);;
write.flush();
out.close();
write.close();
} catch (FileNotFoundException e) {
// TODO: handle exception
System.out.println("无法找到文件!请确认你的路径是否正确。或者文件存在。");
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("发生IO错误,请联系管理人员。");
}
}


public void readInDevice(String path){
BufferedReader reader = null;
FileInputStream inputStream = null;
try {
File file = new File(path);
inputStream = new FileInputStream(file);
reader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
int temp = 0;
while ((temp = reader.read()) != -1) {
                System.out.print((char)temp);
            }
inputStream.close();
reader.close();
} catch (FileNotFoundException e) {
// TODO: handle exception
System.out.println("无法找到文件!请确认你的路径是否正确。或者文件存在。");
// e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
System.out.println("不支持的编码格式。");
// e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("发生IO错误,请联系管理人员。");
// e.printStackTrace();
}
}
}

测试类的主要代码

public class Test {

public static void main(String[] args) {
Introduction in = new Introduction();
in.setName("张三");
in.setAge(18);
in.setMajor("计算机应用与技术");
String str = in.introduction();
String path = in.getDafaultPath();
in.writeInDevice(str, path);
in.readInDevice(path);
}


}

第2个回答  2015-04-21
system.in

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网