您的位置:首页 > 编程语言 > Java开发

Java之输入输出流(文件的读写)

2014-08-31 22:03 405 查看
Java之输入输出流(文件的读写)
首先,在编程的世界,流明显显得很重要。C++的输入输出流,Java的输入输出流等等。

首先我们得学会如何使用Java的输入输出流。首先,它们被封装在Java的一个叫做java.io的包中,编程时也必须导入此包。
我们首先编写一个程序,此程序能够简单的使用到Java语言的输入输出流。
编写一个简单的文件写入 和读出的操作。(源代码如下)
importjava.io.*;
publicclassTest1
{
publicstaticvoidmain(String[]
args) throwsIOException {
StringfilePath =
"D:\\c.txt";
FileWriterwriter =
newFileWriter(filePath);
writer.write("HelloMy
name is Jack_Li.\r\n");
//可以写入英文
writer.write("你好,我的名字是杰克.\r\n");
//也可以写入中文 字节码内部转换
writer.close();

}
}
运行以上程序,即可在D盘下建立一个c.txt文件,并且显示的内容即为程序中写入的内容。
好了,我们现在剖析一下程序,首先,在文件写入和读出过程中,可能会出现,文件写入或读出的错误,一般会使用异常。这里简单的抛出一个IO异常,现在是FileWriter这个类是干嘛的?
打开JDK(这里版本是1.6.0),文档如是道:
publicclass
FileWriter
extendsOutputStreamWriter

用来写入字符文件的便捷类。此类的构造方法假定默认字符编码和默认字节缓冲区大小都是可接受的。要自己指定这些值,可以先在FileOutputStream上构造一个OutputStreamWriter。

文件是否可用或是否可以被创建取决于底层平台。特别是某些平台一次只允许一个FileWriter(或其他文件写入对象)打开文件进行写入。在这种情况下,如果所涉及的文件已经打开,则此类中的构造方法将失败。

FileWriter用于写入字符流。要写入原始字节流,请考虑使用FileOutputStream。

我们可以清洗的看见大它的功能是什么。

这个类的方法主要包括从java.io.OutputStreamWriter继承的方法,从java.io.Writer继承的方法,从java.lang.Object继承的方法(此方法所有类都继承),使用时便可查阅文档。

现在介绍一下文件的读出操作。请看源代码
importjava.io.*;
//进行数据的读取
publicclassTest2
{

publicstaticvoidmain(String[]
args) throwsIOException{
StringfilePath =
"D:\\c.txt";
Stringline;
BufferedReaderin=
newBufferedReader(newFileReader(filePath));
line=
in.readLine();
while(line!=
null)
{
System.out.println(line);
line=
in.readLine();
}
in.close();
}
}

此时文件的读取使用了BufferedReader类,此类进行文件的读取比较方便而且高效。(类的情况介绍详见JDK)。

文件输入输出的扩展,首先我们可以简单的编写一个单文档程序,模拟文件中的打开和保存功能,并且添加基本的复制,粘贴,剪贴功能。

源程序如下:
importjava.awt.*;
importjava.awt.event.*;
importjava.io.*;
importjavax.swing.*;
//利用JTextArea
此类方法比较多
importjava.util.Date;
importjava.text.SimpleDateFormat;
classeditMenu
{
privateJFrame
f;
privateJTextArea
ta;
privateJMenuBar
mb;
privateJMenu
editMenuItem;
privateJMenuItem
copyMenuItem;
//复制
privateJMenuItem
cutMenuItem;
//剪贴
privateJMenuItem
pastMenuItem;
//粘贴
privateJMenuItem
timeMenuItem;
editMenu(JFramef,JMenuBar mb,JTextArea ta)
{
this.f=
f;
this.mb=
mb;
this.ta=
ta;
initAllEditMenu();
editEvent();
}
privatevoidinitAllEditMenu()
{
editMenuItem=
newJMenu("编辑");
copyMenuItem=
newJMenuItem("复制");
cutMenuItem=
newJMenuItem("剪贴");
pastMenuItem=
newJMenuItem("粘贴");
timeMenuItem=
newJMenuItem("时间");

editMenuItem.add(copyMenuItem);
editMenuItem.add(cutMenuItem);
editMenuItem.add(pastMenuItem);
editMenuItem.add(timeMenuItem);
mb.add(editMenuItem);
}
privatevoideditEvent()
{

copyMenuItem.addActionListener(newActionListener()
//复制按钮的响应事件
{
publicvoidactionPerformed(ActionEvent
e)
{
ta.copy();
}
}
);

cutMenuItem.addActionListener(newActionListener()
//剪贴按钮的响应事件
{
publicvoidactionPerformed(ActionEvent
e)
{
ta.cut();
}
}
);

pastMenuItem.addActionListener(newActionListener()
//粘贴按钮的响应事件
{
publicvoidactionPerformed(ActionEvent
e)
{
ta.paste();
}
}
);

timeMenuItem.addActionListener(newActionListener()
{
publicvoidactionPerformed(ActionEvent
e)
{
SimpleDateFormatdf =
newSimpleDateFormat("yyyy-MM-ddHH:mm:ss");
StringstrTime = df.format(newDate());
ta.append(strTime);
}
}
);

}
}
classfileMenu
{
privateJFrame
f;
privateJTextArea
ta;
privateJMenuBar
mb;
privateJMenu
fileMenuItem;
privateJMenuItem
openMenuItem;
privateJMenuItem
saveMenuItem;
privateJMenuItem
exit;
fileMenu(JFramef,JMenuBar mb,JTextArea ta)
{
this.f=
f;
this.ta=
ta;
this.mb=
mb;
initAllFileMenu();
fileEvent();
}
privatevoidinitAllFileMenu()
{
fileMenuItem=
newJMenu("文件");
openMenuItem=
newJMenuItem("打开");
saveMenuItem=
newJMenuItem("保存");
exit=
newJMenuItem("退出");
fileMenuItem.add(openMenuItem);
fileMenuItem.add(saveMenuItem);
fileMenuItem.add(exit);
mb.add(fileMenuItem);
}
privatevoidfileEvent()
{

exit.addActionListener(newActionListener()
//退出按钮的响应事件
{
publicvoidactionPerformed(ActionEvent
e)
{
System.exit(0);
}
}
);
openMenuItem.addActionListener(newActionListener()
{
publicvoidactionPerformed(ActionEvent
e)
{
FileDialogopenDlg =
newFileDialog(f,"打开",FileDialog.LOAD);
openDlg.setVisible(true);

StringstrPath = openDlg.getDirectory();
StringstrFile = openDlg.getFile();
StringfilePath = strPath+strFile;
ta.setText("");
//保障当前区域为空
try
{
BufferedReaderbf =
newBufferedReader(newFileReader(filePath));
StringdataInput =
null;

while((dataInput=
bf.readLine()) != null)
{
ta.append(dataInput+"\r\n");
//加上\r\n表示windows文件的结束标志
}
bf.close();
}
catch(IOExceptionee)
{
thrownewRuntimeException("打开文件有错误");
}

}
}
);
saveMenuItem.addActionListener(newActionListener()
{
publicvoidactionPerformed(ActionEvent
e)
{
StringstrPath =
f.getTitle();
//获取文件的名称
strPath+=
".txt";
//设置为txt文档
try{
BufferedWriterbw =
newBufferedWriter(newFileWriter(strPath));
Stringdata =
ta.getText();
bw.write(data);
bw.close();
}
catch(Exceptionee)
{
newRuntimeException("保存失败");
}

}
}
);
}
}
classMyFrame
{
privateJFrame
noteFrame;
privateJMenuBar
mb;
privateJTextArea
ta;
//表示文本区域
publicMyFrame()
{
InitAll();
}
privatevoidInitAll()
{
noteFrame=
newJFrame("单文档程序练习");
mb=
newJMenuBar();
ta=
newJTextArea();
noteFrame.setSize(800,600);
noteFrame.setLocation(200,80);

newfileMenu(noteFrame,mb,ta);
neweditMenu(noteFrame,mb,ta);
noteFrame.setJMenuBar(mb);
noteFrame.add(ta);

frameEvent();
noteFrame.setVisible(true);
}
privatevoidframeEvent()
{
noteFrame.addWindowListener(newWindowAdapter()
{
publicvoidwindowClosing(WindowEvent
e)
{
System.exit(0);
}
}
);

}
}
publicclassProject
{
publicstaticvoidmain(String[]
args) {
newMyFrame();
}

}

正好,此时我们已经完成一个简单单文档的制作,(有兴趣的朋友可以对其添加功能,使得和Windows的notepad想媲美,不过个人觉得这个有点浪费时间,觉得效率太低。以后哥们会拿出Win32编写的单文档程序)。

基本输入输出流失可以干大事的。

现在我们利用输入输出流,简单模拟一下FTP程序的文件上传功能。

从客户端上传到服务器端。首先选择一下协议(由于文件传输过程中要保证数据的完整性,所以应该使用TCP/IP协议)
importjava.io.*;
importjava.net.*;
classFileClient
{
publicstaticvoidmain(String
args[]) throwsException
{
Sockets =
newSocket("127.0.0.1",10004);

BufferedReader br =
newBufferedReader(
newFileReader("D:\\Client.txt"));

PrintWriterout =
newPrintWriter(s.getOutputStream(),true);
Stringline =
null;
while((line=br.readLine())!=
null)
{
out.println(line);
}
out.println("over");
//输出一个结束标志
BufferedReaderbufIn =
newBufferedReader(
newInputStreamReader(s.getInputStream()));

Stringstr = bufIn.readLine();
System.out.println(str);
br.close();
s.close();
}

}
classFileServer
{
publicstaticvoidmain(String
args[]) throwsException
{
ServerSocketss =
newServerSocket(10004);
Sockets = ss.accept();

BufferedReaderbr =
newBufferedReader(
newInputStreamReader(s.getInputStream()));

PrintWriterout =
newPrintWriter(newFileWriter("D:\\Server.txt"),true);

Stringstr=
null;
while((str=br.readLine())
!= null)
//防止卡死 发送一个结束标志
{
if(str.equals("over"))
break;
out.println(str);
}
PrintWriterpw =
newPrintWriter(s.getOutputStream(),true);
pw.println("Sendfile
successfully!");
br.close();
s.close();
}

}
其中很多涉及流的转换读者可以仔细品味。
读者可以写出C++或者C语言的简单文件传送。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: