Ⅰ java用线程编写一个读写文件的程序,允许多个读者同时读文件,仅允许一个读者写文件。程序没输出
线程的使用有两种方式,第一种是集成Thread类,第二种就是实现Runnable 接口
运行实现Runnable 接口的专程属序,必须使用 线程 例如 new Thread(new ReaderWriter()).start();
还有就是线程的状态你没有掌握,建议你去学习下。
Ⅱ java,编写一个程序,可以读取文件数据
packagedome.myword.test;
importjava.io.BufferedInputStream;
importjava.io.BufferedReader;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.FileReader;
importjava.io.IOException;
publicclassMyword{
publicstaticvoidmain(String[]args)throwsIOException{
{
FileInputStreamfile=newFileInputStream("e:/myText.txt");
BufferedInputStreamBfile=newBufferedInputStream(file);
byte[]b=newbyte[1024];
Strings="";
intbytesRead=0;
while((bytesRead=Bfile.read(b))!=-1){
s+=newString(b,0,bytesRead);
}
System.out.println(s);
String[]words=s.split("");
intsum=words.length;
intmax=words[0].length();
StringmaxWord="";
intavgs=0;
for(inti=1;i<words.length;i++){
if(words[i].length()>max){
max=Math.max(max,words[i].length());
maxWord=words[i];
}
avgs=avgs+words[i].length()+words[0].length();
}
Stringpath="e:/myText.txt";
FileReaderfr=newFileReader(path);
BufferedReaderbr=newBufferedReader(fr);
intx=0;
while(br.readLine()!=null){
x++;
}
System.out.println("总行数"+x);
intavg=avgs/sum;
System.out.println("平均长度:"+avg);
System.out.println("最长单词:"+maxWord);
System.out.println("单词总数:"+sum);
Bfile.close();
StringfileName="e:/mytextdata.txt";
FileOutputStreamout=newFileOutputStream(fileName);
Stringstr="单词总数:"+sum+" "+"总行数:"+x+" "+"最长单词:"+maxWord+" "+"平均长度:"+avg;
out.write(str.getBytes());
out.close();
System.out.println("输出文本完毕");
}catch(FileNotFoundExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}
有问题再叫我。下面是测试结果
Ⅲ java中对文件进行读写操作的基本类是什么
Java.io包中包括许多类提供许多有关文件的各个方面操作。
1 输入输出抽象基类InputStream/OutputStream ,实现文件内容操作的基本功能函数read()、 write()、close()、skip()等;一般都是创建出其派生类对象(完成指定的特殊功能)来实现文件读写。在文件读写的编程过程中主要应该注意异常处理的技术。
2 FileInputStream/FileOutputStream:
用于本地文件读写(二进制格式读写并且是顺序读写,读和写要分别创建出不同的文件流对象);
本地文件读写编程的基本过程为:
① 生成文件流对象(对文件读操作时应该为FileInputStream类,而文件写应该为FileOutputStream类);
② 调用FileInputStream或FileOutputStream类中的功能函数如read()、write(int b)等)读写文件内容;
③ 关闭文件(close())。
3 PipedInputStream/PipedOutputStream:
用于管道输入输出(将一个程序或一个线程的输出结果直接连接到另一个程序或一个线程的输入端口,实现两者数据直接传送。操作时需要连结);
4管道的连接:
方法之一是通过构造函数直接将某一个程序的输出作为另一个程序的输入,在定义对象时指明目标管道对象
PipedInputStream pInput=new PipedInputStream();
PipedOutputStream pOutput= new PipedOutputStream(pInput);
方法之二是利用双方类中的任一个成员函数 connect()相连接
PipedInputStream pInput=new PipedInputStream();
PipedOutputStream pOutput= new PipedOutputStream();
pinput.connect(pOutput);
5 管道的输入与输出:
输出管道对象调用write()成员函数输出数据(即向管道的输入端发送数据);而输入管道对象调用read()成员函数可以读起数据(即从输出管道中获得数据)。这主要是借助系统所提供的缓冲机制来实现的。
6随机文件读写:
RandomAccessFile类(它直接继承于Object类而非InputStream/OutputStream类),从而可以实现读写文件中任何位置中的数据(只需要改变文件的读写位置的指针)。
随机文件读写编程的基本过程为:
① 生成流对象并且指明读写类型;
② 移动读写位置;
③ 读写文件内容;
④ 关闭文件。
七里河团队答疑助人,希望我的回答对你有所帮助