「java如何读写文件代码」JAVA文件读写

博主:adminadmin 2022-12-31 11:54:09 608

本篇文章给大家谈谈java如何读写文件代码,以及JAVA文件读写对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

java怎样实现读写TXT文件

主要有用到java原生态的Io类,没有第三个包。直接上代码:

import java.io.*;

public class write {

    public static void main(String[] args) {

        write("E://123.txt", "hello");

    }

    public static void write(String path, String content) {

        try {

            File f = new File(path);

            

            if (f.exists()) {

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

            } else {

                System.out.println("文件不存在,正在创建...");

                if (f.createNewFile()) {

                    System.out.println("文件创建成功!");

                } else {

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

                }

            }

            BufferedWriter output = new BufferedWriter(new FileWriter(f));

            output.write(content);

            output.close();

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

java读取文本文件代码

java读取文本文件的方法有很多 这个例子主要介绍最简单 最常用的BufferedReader类 完整例子如下 package net chinaunix blog hzm text;import java io BufferedReader;import java io FileReader;import java io IOException;public class ReadFile {private String path;public ReadFile(String filePath){path = filePath;}public String[] openFile() throws IOException{FileReader fr = new FileReader(path) BufferedReader textReader = new BufferedReader(fr) String[] textData = new String[readLines()];int i;for(i= ; i readLines() i++){textData[i] = textReader readLine() }textReader close() return textData;}int readLines() throws IOException{FileReader fileToRead = new FileReader(path) BufferedReader bf = new BufferedReader(fileToRead) int numberOfLines = ;@SuppressWarnings( unused )String oneLine;while((oneLine = bf readLine()) != null){numberOfLines++;}bf close() return numberOfLines;}}package net chinaunix blog hzm text;import java io IOException;public class FileData {public static void main(String[] args) throws IOException{String filePath = C:/text txt ;try{ReadFile reader = new ReadFile(filePath) String[] content = reader openFile() int i;for(i= ;icontent length;i++){System out println(content[i]) }}catch(IOException e){System out println( 异常信息 + e getMessage()) }}}java io BufferedReaderThe buffer size may be specified or the default size may be used The default is large enough for most purposes In general each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly such as FileReaders and InputStreamReaders For example BufferedReader in = new BufferedReader(new FileReader( foo in )) will buffer the input from the specified file Without buffering each invocation of read() or readLine() could cause bytes to be read from the file converted into characters and then returned which can be very inefficient Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader java io FileReaderFileReader is meant for reading streams of characters For reading streams of raw bytes consider using a FileInputStream lishixinzhi/Article/program/Java/hx/201311/26249

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("#", "\\\\.");

41 s = s.replace('*', '#');

42 s = s.replaceAll("#", ".*");

43 s = s.replace('?', '#');

44 s = s.replaceAll("#", ".?");

45 s = "^" + s + "$";

46

47 System.out.println(s);

48 Pattern p = Pattern.compile(s);

49 ArrayList list = filePattern(file, p);

50

51 File[] rtn = new File[list.size()];

52 list.toArray(rtn);

53 return rtn;

54 }

55

56 /** *//**

57 * @param file File 起始文件夹

58 * @param p Pattern 匹配类型

59 * @return ArrayList 其文件夹下的文件夹

60 */

61

62 private static ArrayList filePattern(File file, Pattern p) {

63 if (file == null) {

64 return null;

65 }

66 else if (file.isFile()) {

67 Matcher fMatcher = p.matcher(file.getName());

68 if (fMatcher.matches()) {

69 ArrayList list = new ArrayList();

70 list.add(file);

71 return list;

72 }

73 }

74 else if (file.isDirectory()) {

75 File[] files = file.listFiles();

76 if (files != null files.length 0) {

77 ArrayList list = new ArrayList();

78 for (int i = 0; i files.length; i++) {

79 ArrayList rlist = filePattern(files[i], p);

80 if (rlist != null) {

81 list.addAll(rlist);

82 }

83 }

84 return list;

85 }

86 }

87 return null;

88 }

89

90 /** *//**

91 * 测试

92 * @param args String[]

93 */

94 public static void main(String[] args) {

95 }

96}

Java如何读写txt文件的代码

有关Java如何读写txt文件这个问题经常在面试时会被问到,不懂或不熟悉的同志们可是要记好了哟!先来看下具体实现吧! package common; import java.io.*; import java.util.ArrayList; public class IOTest { public static void main (String args[]) { ReadDate(); WriteDate(); } /** * 读取数据 */ public static void ReadDate() { String url = “e:/2.txt”; try { FileReader read = new FileReader(new File(url)); StringBuffer sb = new StringBuffer(); char ch[] = new char[1024]; int d = read.read(ch); while(d!=-1){ String str = new String(ch,0,d); sb.append(str); d = read.read(ch); } System.out.print(sb.toString()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * 写入数据 */ public static void WriteDate() { try{ File file = new File(“D:/abc.txt”); if (file.exists()) { file.delete(); } file.createNewFile(); BufferedWriter output = new BufferedWriter(new FileWriter(file)); ArrayList ResolveList = new ArrayList(); for (int i = 0; i 10; i++) { ResolveList.add(Math.random()* 100); } for (int i=0 ;i output.write(String.valueOf(ResolveList.get(i)) + “\n”); } output.close(); } catch (Exception ex) { System.out.println(ex); } } }

java如何读取txt文件?

首先你要定义一条文件路线。就是实例File这个类,这条路连接了你的磁盘,也就是文件处,和你的代码处,你需要一个外卖员帮你传输数据,就是流,实例流对象!然后就是读取,用read方法读,每次读取的数据,存进字节数组,然后传进String类的构造器,底层会给你把字节数组里的转为字符串,就读取出来了,

关于java如何读写文件代码和JAVA文件读写的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。