use std::fs::{File, OpenOptions};
use std::io::{self, BufReader, BufWriter, Read, Write};
use std::path::Path;
use e9571_file_lib::e9571_file_lib::check_file_is_exist;
use std::time::Instant;
use std::collections::HashMap;
pub mod e9571_io_lib {
use std::fs;
use std::io::BufRead;
use super::*;
pub fn create_source(path: &str) -> Result<Vec<String>, io::Error> {
let mut data_buffer = Vec::new();
let file = File::open(path)?;
let mut reader = BufReader::new(file);
let mut line = String::new();
while reader.read_line(&mut line)? > 0 {
data_buffer.push(line.trim().to_string());
line.clear();
}
Ok(data_buffer)
}
pub fn write_file(str: &str, path: &str) -> io::Result<()> {
let mut file = if check_file_is_exist(path) {
OpenOptions::new().write(true).append(true).open(path)?
} else {
OpenOptions::new().write(true).create(true).open(path)?
};
file.write_all(str.as_bytes())?;
file.sync_all()?;
Ok(())
}
pub fn write_line(str: &str, file_path: &str) -> io::Result<()> {
if !check_file_is_exist(file_path) {
File::create(file_path)?;
}
let file = OpenOptions::new().read(true).write(true).append(true).open(file_path)?;
let mut writer = BufWriter::new(file);
writer.write_all(str.as_bytes())?;
writer.flush()?;
Ok(())
}
pub fn write_to_file(file_name: &str, content: &str) -> io::Result<()> {
let mut file = OpenOptions::new()
.write(true)
.truncate(true)
.create(true)
.open(file_name)?;
file.write_all(content.as_bytes())?;
file.sync_all()?;
Ok(())
}
pub fn write_list_to_file(list: &[String], file_path: &str) -> io::Result<()> {
let file = File::create(file_path)?;
let mut writer = BufWriter::new(file);
for line in list {
writeln!(writer, "{}", line)?;
}
writer.flush()?;
Ok(())
}
pub fn write_map_to_file(m: &HashMap<String, String>, file_path: &str) -> io::Result<()> {
let file = File::create(file_path)?;
let mut writer = BufWriter::new(file);
for (k, v) in m {
writeln!(writer, "{}^{}", k, v)?;
}
writer.flush()?;
Ok(())
}
pub fn read_all_byte(file_path: &str) -> Result<Vec<u8>, io::Error> {
let mut file = OpenOptions::new().append(true).open(file_path)?;
let mut buffer = Vec::new();
file.read_to_end(&mut buffer)?;
Ok(buffer)
}
pub fn read_all_byte_linux(file_path: &str) -> Result<Vec<u8>, io::Error> {
fs::read(file_path)
}
pub fn read_block(file_path: &str) -> String {
let start = Instant::now();
let mut note = String::new();
let mut count = 0;
let file = match File::open(file_path) {
Ok(file) => file,
Err(e) => {
println!("{}", e);
return String::new();
}
};
let mut reader = BufReader::new(file);
let mut buffer = vec![0; 20_480];
loop {
match reader.read(&mut buffer) {
Ok(n) if n > 0 => {
note.push_str(&String::from_utf8_lossy(&buffer[..n]));
count += 1;
}
Ok(_) => break, Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
Err(e) => {
println!("{}", e);
break;
}
}
}
println!("readBlock spend: {:?}", start.elapsed());
note
}
pub fn path_standard(path: &str) -> String {
path.replace("\\", "/")
}
}