日期:2014-05-20  浏览次数:20875 次

怎樣用java寫入和讀取txt或excel文件
怎樣用java寫入和讀取txt或excel文件,能否請代碼做個例子。
或講解一下java寫入和讀取的步驟。

------解决方案--------------------
其实用流就行了,一般建意用缓冲流(BufferedReader用于读,BufferedWriter用于写)下面写一个操作txt文件的例子:
/**
* 读文件
* @param path 要读入文件的路径
* @return 读入的文件的内容
*/
public String readText(String path){
BufferedReader is=null;
String tem="";
StringBuffer content = new StringBuffer();
try {
is=new BufferedReader(new FileReader(path));
while((tem=is.readLine())!=null){
content.append(tem).append("\n");
}
}catch(Exception e){
System.err.println("文件读取错误!");
}finally{
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return content.toString();
}
/**
* 写文件
* @param path 文件的路径
* @param content 写入文件的内容
*/
public void writerText(String path,String content){
try {
BufferedWriter bw1=new BufferedWriter(new FileWriter(path));
bw1.write(content);
bw1.flush();
bw1.close();
} catch (IOException e) {
e.printStackTrace();
}

}

------解决方案--------------------

我以前写的东西,你可以借着参考一下……
public class Pro7 {
public static void readfile() {
try {
File file = new File("d:\\shu\\trad-simp.utf-8");
File file1 = new File("d:\\shu\\input-pinyin.utf-8");

InputStream input = new FileInputStream(file);
InputStream input1 = new FileInputStream(file1);

InputStreamReader inputreader =
new InputStreamReader(new FileInputStream(file), "UTF-8");
InputStreamReader inputreader1 =
new InputStreamReader(new FileInputStream(file1), "UTF-8");

BufferedReader buffer = new BufferedReader(inputreader);
BufferedReader buffer1 = new BufferedReader(inputreader1);

String str1 = new String();
String str2 = new String();
String str3 = new String();

char[] ch = new char[10000];
char[] ch1 = new char[5000];
char[] ch2 = new char[3000];
byte[] by = new byte[540000];

OutputStream out = new FileOutputStream("c:\\chinese\\text1.txt");

int j = 0;
int k = 0;

if (input1.read(by) != -1) {
str3 = new String(by, "utf-16");
}

if (buffer.read(ch) != -1) {
for (int i = 0; i < 10000; i = i + 4) {
ch1[j++] = ch[i];
}
for (int i = 2; i < 10000; i = i + 4) {
ch2[k++] = ch[i];
}
}

str1 = String.valueOf(ch1);
str2 = String.valueOf(ch2);

System.out.println(str1);
System.out.println(str2);
for (int i = 0; i < 5000; i++) {
for (int l = 0; l < 260000; l++) {
if (str1.charAt(i) == str3.charAt(l)) {
System.out.println("str3的第 " + l + " 个字符需要替换");
System.out.println(
str2.charAt(i) + "替换" + str3.charAt(l));

str3 = str3.replace(str3.charAt(l), str2.charAt(i));

}
}
}
System.out.println(str3);
by = str3.getBytes();
out.write(by);

out.close();
input.close();
input1.close();
inputreader.close();
inputreader1.close();
buffer.close();
buffer1.close();
} catch (IOException e) {
System.err.println(e);
}

}

public static void main(String[] args) {
readfile();

}
}

------解决方案--------------------
excle文件的读写, 建议用poi, 或jxl都可