java读写文件的笔记

读文件

12=Pop Music一个example的函数调用我的searchBySongType接口,example传递Pop Music给searchBySongType。searchBySongType拿到Pop Music后要转换成12再到库里去查询。

13=Pop Music/Classic还有一种就是Pop Music和Classic同时指向13,我是这样处理的:首先要保证Classic能搜到音乐,Pop Music也能搜到音乐。所以Classic和Pop Music为键, 13为值。

key :Pop Music指向value:12, 13 set集合
key:Classic指向 value:13 set集合

这些存放在songType.txt中,我要处理txt文件,将他们转换乘java中的map的键值对形式。

private Map<String, HashSet<String>> SONG_TYPE_REF_MAP = new ConcurrentHashMap<>();

下面是处理songType.txt文本

58=Singer Songwriter/Rock 摇滚/流行/摇滚
29=Miscellaneous
46=R&B/流行/RB 节奏布鲁斯/节奏布鲁斯
13=流行/Pop 流行/K-Pop 韩国流行/Rock 摇滚
61=World Music 世界音乐

java代码

@PostConstruct
    private void init() {
	//加载songType.txt文件
        ClassPathResource classPathResource = new ClassPathResource("songType.txt");
        try (
		//将songType.txt文件转换为流文件一行一行读取
                InputStream is =  classPathResource.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader reader = new BufferedReader(isr);
                ) {
            String line = null;

            while((line = reader.readLine()) != null) {
                String[] temp = line.split("=");
                if (temp.length > 1) {
		    //这里因为是12=Pop Music表示方式,所以temp[1]为key,temp[0]为value
                    String key = temp[1];
                    String value = temp[0];
                    //可能在temp[1]中存在多种属性,所以将他们分隔开成为一个新的键
                    String[] temp_keys = StringUtils.split(key, "/");
                    for (String single_key : temp_keys) {
                        single_key = StringUtils.trimToEmpty(single_key);
                        if (StringUtils.isNotBlank(single_key)) {
                            HashSet<String> values = SONG_TYPE_REF_MAP.get(single_key);
                            if (values == null) {
                                values = new HashSet<>();
                                SONG_TYPE_REF_MAP.put(key, values);
                            }
                            values.add(value);
                        }
                    }


                }

            }
        } catch (Exception e) {

        }
    }

 

读取json文件,将json文件内容一次性转换为string,再转成相应的json

poetry.json存放在resources目录下

[ {"59f859fa5fb61e36f8eee085":"转寿春守,太和庚"},
  {"59f8557a5fb61e1d744058b2":"辛巳除夕与彭同年"},
  {"59f85c465fb61e36f8ef0cbe":"达奚中丞东斋壁画"}
]
JSONArray array = new JSONArray();

try {
    ClassPathResource classPathResource = new ClassPathResource("poetry.json");
    String str = IOUtils.toString(
       new InputStreamReader(
       classPathResource.getInputStream(), StandardCharsets.UTF_8));

    array = JSONObject.parseArray(str);
} catch (Exception e) {
    e.printStackTrace();
}
FileInputStream file = new FileInputStream(path);
//ClassPathResource classPathResource = new ClassPathResource(path);
String str = IOUtils.toString(new InputStreamReader(file, StandardCharsets.UTF_8));

写文件

以properties文件为例子,根据绝对路径读取文件。如果根据查找的路径文件不存在,再新建一个文件

// 从输入流中读取属性列表(键和元素对)
Properties prop = new Properties();
if(StringUtils.isNotBlank(path)) {
	File file = new File(path);
	//如果文件不存在,再新建一个文件
	if(!file.exists()) {
		file.createNewFile();
	}

	FileInputStream fin = new FileInputStream(file);

	prop.load(fin);

	if(StringUtils.isNotBlank(prop.getProperty("spider_album_index"))) {
		pageIndex = Integer.parseInt(prop.getProperty("spider_album_index"));
	}

	fin.close();
}

 

根据绝对路径 写入文件

try {
	Properties prop = new Properties();
	if(StringUtils.isNotBlank(path)) {

		FileOutputStream fos = new FileOutputStream(path);
		prop.setProperty("spider_album_index", String.valueOf(page));
		prop.store(fos, "");

		fos.close();
		fos.flush();
	}
} catch (Exception e) {
	e.printStackTrace();
}

随便定义一个格式,然后将文本内容写入中,读取超大文本excel

FileInputStream in = new FileInputStream("D:/appdata/1229009552/FileRecv/drug_data_xiaofang.xlsx");
String downloadDat = "./xiaofang.dat";
FileOutputStream fos = new FileOutputStream(downloadDat, true);


Workbook wk = StreamingReader.builder()
        .rowCacheSize(100)  //缓存到内存中的行数,默认是10
        .bufferSize(4096)  //读取资源时,缓存到内存的字节大小,默认是1024
        .open(in);  //打开资源,必须,可以是InputStream或者是File,注意:只能打开XLSX格式的文件
Sheet sheet = wk.getSheetAt(0);
//遍历所有的行
for (Row row : sheet) {
    System.out.println("开始遍历第" + row.getRowNum() + "行数据:");
    //遍所有的列
    StringBuilder stringBuilder = new StringBuilder(String.valueOf(row.getRowNum())+"::");
    for (Cell cell : row) {
        stringBuilder.append(cell.getStringCellValue()+"::");
    }
    stringBuilder.append("\r\n");
    fos.write(stringBuilder.toString().getBytes());
}
fos.close();

方法内需要添加如下依赖

<dependency>
   <groupId>com.monitorjbl</groupId>
   <artifactId>xlsx-streamer</artifactId>
   <version>1.2.0</version>
</dependency>

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java提供了很多文件操作的API,以下是常用的文件操作方法: 1. 创建文件 可以使用`File`类的构造方法来创建文件对象,并使用`createNewFile()`方法来创建文件。 ```java File file = new File("test.txt"); if(file.createNewFile()){ System.out.println("文件创建成功!"); }else{ System.out.println("文件已存在!"); } ``` 2. 删除文件 可以使用`delete()`方法来删除文件。 ```java File file = new File("test.txt"); if(file.delete()){ System.out.println("文件删除成功!"); }else{ System.out.println("文件不存在!"); } ``` 3. 读取文件 可以使用`FileReader`或`BufferedReader`类来读取文件。 ```java // FileReader FileReader reader = new FileReader("test.txt"); int c; while((c = reader.read()) != -1){ System.out.print((char)c); } reader.close(); // BufferedReader File file = new File("test.txt"); BufferedReader reader = new BufferedReader(new FileReader(file)); String line; while((line = reader.readLine()) != null){ System.out.println(line); } reader.close(); ``` 4. 写入文件 可以使用`FileWriter`或`BufferedWriter`类来写入文件。 ```java // FileWriter FileWriter writer = new FileWriter("test.txt"); writer.write("Hello World!"); writer.close(); // BufferedWriter File file = new File("test.txt"); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.write("Hello World!"); writer.newLine(); writer.write("Java 文件操作!"); writer.close(); ``` 5. 复制文件 可以使用`FileInputStream`和`FileOutputStream`类来复制文件。 ```java File source = new File("source.txt"); File dest = new File("dest.txt"); try( FileInputStream fis = new FileInputStream(source); FileOutputStream fos = new FileOutputStream(dest) ){ byte[] buffer = new byte[1024]; int length; while((length = fis.read(buffer)) > 0){ fos.write(buffer, 0, length); } System.out.println("文件复制成功!"); }catch(IOException e){ e.printStackTrace(); } ``` 以上是常用的文件操作方法,还有其他更多的文件操作方法,可以查看Java官方文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值