Java使用文件输入输出流的应用程序 (共三题)
代码里面提到的文件需要提前建立
- 将用户从键盘输入的10行字符串存入文件,然后输出文件长度。(提示,用BufferedWriter或RandomAccessFile类写出)
- 将用户从键盘输入的10行字符串存入文件,然后输出文件长度。(提示,用BufferedWriter或RandomAccessFile类写出)
- 写程序判断D盘根目录下a.txt文件是否存在,如果存在则向其内依次写入字符串 “Will Smith”,整数25,写入后再从文件中将其读出。(利用RandomAccessFile类或DataOutputStream,DataInputStream)
import java.io.*;
import java.util.Scanner;
//第一题
class KY10_3 {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
String str[] =new String[10];
for(int i=0;i<10;i++)
{
str[i]=sc.nextLine();
}
try {
RandomAccessFile rf = new RandomAccessFile("D:\\QWew.txt", "rw");
System.out.println("\n 文件指针位置为:" + rf.getFilePointer());
System.out.println("文件的长度为:" + rf.length());
rf.seek(rf.length());
System.out.println("文件指针现在的位置为:" + rf.getFilePointer());
for (int i = 0; i < 10; i++)
rf.writeUTF(str[i]); // 字符串转为字节串添加到文件末尾87
rf.seek(0);
System.out.println("\n 选择显示的文件内容:");
String s;
while (rf.getFilePointer()<rf.length())
{
s = rf.readUTF();
System.out.println(s);
}
rf.close();
} catch (FileNotFoundException fnoe) {
} catch (IOException ioe) {
}
}
}
这里使用的是RandomAccessFile,下同
import java.io.*;
import java.util.Scanner;
//第二题
public class second {
public static void main(String args[]) {
int a[]=new int[10];
Scanner sc = new Scanner(System.in);
for(int i=0;i<10;i++)
{
a[i]=sc.nextInt();
}
// String str[] = { "First line\n", "Second line\n", "Last line\n" };
try {
RandomAccessFile rf = new RandomAccessFile("D:\\ioliu.txt", "rw");
System.out.println("\n 文件指针位置为:" + rf.getFilePointer());
System.out.println("文件的长度为:" + rf.length());
rf.seek(rf.length());
System.out.println("文件指针现在的位置为:" + rf.getFilePointer());
for (int i = 0; i < 10; i++)
rf.writeInt(a[i]); // 字符串转为字节串添加到文件末尾87
rf.seek(0);
System.out.println("\n 选择显示的文件内容:");
int s;
while (rf.getFilePointer()<rf.length()){//
s = rf.readInt();
System.out.println(s);}
rf.close();
} catch (FileNotFoundException fnoe) {
} catch (IOException ioe) {
}
}
}
import java.io.*;
//第三题
public class FieldSeek
{
public static void main(String args[]) throws IOException
{
boolean s1;
String s2="Will Smith";
int s3=25;
File dir=new File("D:/","a.txt");
s1=dir.exists();
if(s1)
{
try
{
RandomAccessFile rf2 = new RandomAccessFile("D:\\a.txt","rw");
rf2.seek(rf2.length());
rf2.writeUTF(s2);
rf2.writeInt(s3);
rf2.seek(0);
s2=rf2.readUTF();
s3=rf2.readInt();
System.out.println(s2);
System.out.println(s3);
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//System.out.println("存在");
}
}