首页 > 编程知识 正文

java文件读写的问题,java 文件读写

时间:2023-12-27 22:27:54 阅读:326960 作者:CZDA

本文目录一览:

Java文件读写

实用的模糊(通配符)文件查找程序

1 import java.io.File;

2 import java.util.regex.Matcher;

3 import java.util.regex.Pattern;

4 import java.util.ArrayList;

5

6 /** *//**

7 * pTitle: FileService /p 8* pDescription: 获取文件 /p 9* pCopyright: Copyright (c) 2007/p

10* pCompany: /p

11* @author not attributable

12* @version 1.0

13*/

14public class FileService {

15 public FileService() {

16 }

17

18 /** *//**

19 * 在本文件夹下查找

20 * @param s String 文件名

21 * @return File[] 找到的文件

22 */

23 public static File[] getFiles(String s)

24 {

25 return getFiles("./",s);

26 }

27

28 /** *//**

29 * 获取文件

30 * 可以根据正则表达式查找

31 * @param dir String 文件夹名称

32 * @param s String 查找文件名,可带*.?进行模糊查询

33 * @return File[] 找到的文件

34 */

35 public static File[] getFiles(String dir,String s) {

36 //开始的文件夹

37 File file = new File(dir);

38

39 s = s.replace('.', '#');

40 s = s.replaceAll("#", "\\.");

java读取写入文件问题

java 追加内容到文件末尾的几种常用方法

import java.io.FileWriter;

import java.io.IOException;

import java.io.RandomAccessFile;

public class AppendToFile {

/**

* A方法追加文件:使用RandomAccessFile

*/

public static void appendMethodA(String fileName, String content) {

try {

// 打开一个随机访问文件流,按读写方式

RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");

// 文件长度,字节数

long fileLength = randomFile.length();

//将写文件指针移到文件尾。

randomFile.seek(fileLength);

randomFile.writeBytes(content);

randomFile.close();

} catch (IOException e) {

e.printStackTrace();

}

}

/**

* B方法追加文件:使用FileWriter

*/

public static void appendMethodB(String fileName, String content) {

try {

//打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件

FileWriter writer = new FileWriter(fileName, true);

writer.write(content);

writer.close();

} catch (IOException e) {

e.printStackTrace();

}

}

public static void main(String[] args) {

String fileName = "E:/newTemp.dat";

String content = "new append!";

//按方法A追加文件

AppendToFile.appendMethodA(fileName, content);

AppendToFile.appendMethodA(fileName, "append end.");

//显示文件内容

ReadFromFile.readFileByBytes(fileName);//.readFileByLines(fileName);

/* //按方法B追加文件

AppendToFile.appendMethodB(fileName, content);

AppendToFile.appendMethodB(fileName, "append end. n");

//显示文件内容

ReadFromFile.readFileByBytes(fileName);*/

// ReadFromFile.readFileByLines(fileName);

}

}

java 文件读写问题

看你两个截图 是要往文件里面加一个数25

但是你描述的是读一个 数出来 加上25 然后再写入文件。。。。需求说清楚

JAVA的文件读写问题

当热身了~import java.io.BufferedWriter;

import java.io.FileWriter;

import java.util.*;/*编写一个程序,用于从键盘读入信息,并存储到磁盘文件中去。

要求:1. 以行的方式读入姓名和学号信息,例如:张三 20071215 (姓名和学号中间用一个空格隔开)

2. 循环读入,直到用户输入“quit”或者“QUIT”结束

3. 程序提示要用户输入一个文件名,例如:请输入存储到的文件名: userlist.txt

4. 在整个上述过程中,要做例外处理;如果文件创建成功,则给出提示信息。*/public class test9

{

public static void main(String[] args)

{

T1();

}

public static void T1()

{

FileWriter out ;

BufferedWriter bw;

String fileName = null;

String message = null;

Scanner scanner = new Scanner(System.in);

System.out.print("请输入存储到的文件名:");

fileName = scanner.next();

try

{

out = new FileWriter(fileName);

bw = new BufferedWriter(out);

System.out.print("n文件创建成功!n请输入姓名和学号信息:");

while( !(message = scanner.next()).equalsIgnoreCase("quit"))

{

bw.write(message);

bw.newLine();

}

bw.close();

out.close();

}

catch(Exception e)

{

System.out.println("文件创建失败!");

}

}} import java.util.Scanner;

import java.io.*;/*再编写一个程序,用于从上述存储的磁盘文件中读出信息,并显示在屏幕上。

要求:

1)文件名从键盘输入;

2)姓名和学号分开显示,例如屏幕显示如下信息:

文件 userlist.txt 中存储的姓名有: 张三 李四王五 ……

文件userlist.txt 中存储的学号有: 20061215 20061317 20061425 ….. */

public class test10

{

public static void main(String[] args)

{

T2();

}

public static void T2()

{

FileReader read;

BufferedReader in ;

Scanner scanner = new Scanner(System.in);

String fileName = null;

String message = null;

String[] buf = new String[2];

String[] name = new String[10];

String[] number = new String[10];

int pos1 = 0;

int pos2 = 0;

System.out.print("请输入要读取的文件名:");

fileName = scanner.next();

try

{

read = new FileReader(fileName);

in = new BufferedReader(read);

while((message = in.readLine()) != null)

{

buf = message.split(" ");

name[pos1++] = buf[0];

number[pos2++] = buf[1];

buf = new String[2];

}

}

catch(Exception e)

{

System.out.println("该文件不存在!");

}

System.out.println( "屏幕显示如下信息:");

System.out.print("文件"+fileName+"中存储的姓名有:");

for(int i = 0; name[i] != null;i++)

{

System.out.print(name[i]+" ");

}

System.out.print("n文件"+fileName+"中存储的学号有:");

for(int i = 0; number[i] != null;i++)

{

System.out.print(number[i]+" ");

}

}}

java 读写文件异常怎么处理

public class ReadFromFile {

    /**

     * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。

     */

    public static void readFileByBytes(String fileName) {

        File file = new File(fileName);

        InputStream in = null;

        try {

            System.out.println("以字节为单位读取文件内容,一次读一个字节:");

            // 一次读一个字节

            in = new FileInputStream(file);

            int tempbyte;

            while ((tempbyte = in.read()) != -1) {

                System.out.write(tempbyte);

            }

            in.close();

        } catch (IOException e) {

            e.printStackTrace();

            return;

        }

        try {

            System.out.println("以字节为单位读取文件内容,一次读多个字节:");

            // 一次读多个字节

            byte[] tempbytes = new byte[100];

            int byteread = 0;

            in = new FileInputStream(fileName);

            ReadFromFile.showAvailableBytes(in);

            // 读入多个字节到字节数组中,byteread为一次读入的字节数

            while ((byteread = in.read(tempbytes)) != -1) {

                System.out.write(tempbytes, 0, byteread);

            }

        } catch (Exception e1) {

            e1.printStackTrace();

        } finally {

            if (in != null) {

                try {

                    in.close();

                } catch (IOException e1) {

                }

            }

        }

    }

  

    /**

     * 以字符为单位读取文件,常用于读文本,数字等类型的文件

     */

    public static void readFileByChars(String fileName) {

        File file = new File(fileName);

        Reader reader = null;

        try {

            System.out.println("以字符为单位读取文件内容,一次读一个字节:");

            // 一次读一个字符

            reader = new InputStreamReader(new FileInputStream(file));

            int tempchar;

            while ((tempchar = reader.read()) != -1) {

                // 对于windows下,rn这两个字符在一起时,表示一个换行。

                // 但如果这两个字符分开显示时,会换两次行。

                // 因此,屏蔽掉r,或者屏蔽n。否则,将会多出很多空行。

                if (((char) tempchar) != 'r') {

                    System.out.print((char) tempchar);

                }

            }

            reader.close();

        } catch (Exception e) {

            e.printStackTrace();

        }

        try {

            System.out.println("以字符为单位读取文件内容,一次读多个字节:");

            // 一次读多个字符

            char[] tempchars = new char[30];

            int charread = 0;

            reader = new InputStreamReader(new FileInputStream(fileName));

            // 读入多个字符到字符数组中,charread为一次读取字符数

            while ((charread = reader.read(tempchars)) != -1) {

                // 同样屏蔽掉r不显示

                if ((charread == tempchars.length)

                         (tempchars[tempchars.length - 1] != 'r')) {

                    System.out.print(tempchars);

                } else {

                    for (int i = 0; i  charread; i++) {

                        if (tempchars[i] == 'r') {

                            continue;

                        } else {

                            System.out.print(tempchars[i]);

                        }

                    }

                }

            }

  

        } catch (Exception e1) {

            e1.printStackTrace();

        } finally {

            if (reader != null) {

                try {

                    reader.close();

                } catch (IOException e1) {

                }

            }

        }

    }

  

    /**

     * 以行为单位读取文件,常用于读面向行的格式化文件

     */

    public static void readFileByLines(String fileName) {

        File file = new File(fileName);

        BufferedReader reader = null;

        try {

            System.out.println("以行为单位读取文件内容,一次读一整行:");

            reader = new BufferedReader(new FileReader(file));

            String tempString = null;

            int line = 1;

            // 一次读入一行,直到读入null为文件结束

            while ((tempString = reader.readLine()) != null) {

                // 显示行号

                System.out.println("line " + line + ": " + tempString);

                line++;

            }

            reader.close();

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            if (reader != null) {

                try {

                    reader.close();

                } catch (IOException e1) {

                }

            }

        }

    }

  

    /**

     * 随机读取文件内容

     */

    public static void readFileByRandomAccess(String fileName) {

        RandomAccessFile randomFile = null;

        try {

            System.out.println("随机读取一段文件内容:");

            // 打开一个随机访问文件流,按只读方式

            randomFile = new RandomAccessFile(fileName, "r");

            // 文件长度,字节数

            long fileLength = randomFile.length();

            // 读文件的起始位置

            int beginIndex = (fileLength  4) ? 4 : 0;

            // 将读文件的开始位置移到beginIndex位置。

            randomFile.seek(beginIndex);

            byte[] bytes = new byte[10];

            int byteread = 0;

            // 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。

            // 将一次读取的字节数赋给byteread

            while ((byteread = randomFile.read(bytes)) != -1) {

                System.out.write(bytes, 0, byteread);

            }

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            if (randomFile != null) {

                try {

                    randomFile.close();

                } catch (IOException e1) {

                }

            }

        }

    }

  

    /**

     * 显示输入流中还剩的字节数

     */

    private static void showAvailableBytes(InputStream in) {

        try {

            System.out.println("当前字节输入流中的字节数为:" + in.available());

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

  

    public static void main(String[] args) {

        String fileName = "C:/temp/newTemp.txt";

        ReadFromFile.readFileByBytes(fileName);

        ReadFromFile.readFileByChars(fileName);

        ReadFromFile.readFileByLines(fileName);

        ReadFromFile.readFileByRandomAccess(fileName);

    }

}

Java文件读写问题

第一 写完文件后,建议进行一次flush

第二 你的main方法中: new test(); 此语句只是创建一个Test的对象并没有执行test()方法,改为 new test().test();

第三 调试阶段,建议你将Exception的信息打印出来.

不谢.

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。