-
2021-02-28 10:44:51
package com.springbootblog.controller;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/**
*@title : JavaClass
*@author:zyh
*@createDate:2018/9/13 21:46
*
**/
@RequestMapping(value = "/queryImg")
@Controller
public class ReadImgController {
@ApiOperation(value = "img", produces = "application/json")
@ApiImplicitParams({
})
@RequestMapping(value = "/img",method = RequestMethod.POST)
@ResponseBody
public void getImage(String path, HttpServletRequest request, HttpServletResponse response) {
try {
String url="D:\\temp-appImg\\20180912\\7cd2e1a3-a087-4e25-aac8-2bdf8e274c6f.png";
File file = new File(url);
String l=request.getRealPath("/")+"/"+url;
String filename = file.getName();
InputStream fis = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
// 设置response的Header
response.addHeader("Content-Length", "" + file.length());
response.setContentType("image/jpg");
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
//return response;
}
@ApiOperation(value = "img", produces = "application/json")
@ApiImplicitParams({
})
@RequestMapping(value = "/imgRes",method = RequestMethod.POST)
@ResponseBody
public HttpServletResponse getImageRes(String path, HttpServletRequest request, HttpServletResponse response) {
try {
String url="D:\\temp-appImg\\20180912\\7cd2e1a3-a087-4e25-aac8-2bdf8e274c6f.png";
File file = new File(url);
String l=request.getRealPath("/")+"/"+url;
String filename = file.getName();
InputStream fis = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
// 设置response的Header
response.addHeader("Content-Length", "" + file.length());
response.setContentType("image/png");
OutputStream toClient = new BufferedOutputStream(response.getOutputStream(),888888);
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return response;
}
@ApiOperation(value = "返回指定地址的文件流1")
@ApiImplicitParams({
@ApiImplicitParam(name = "url", value = "图片地址", required = true,
paramType = "query", defaultValue = "\\20180912\\7cd2e1a3-a087-4e25-aac8-2bdf8e274c6f.png"),
})
@RequestMapping(value = "/noLogin/readImageFile1", method = RequestMethod.POST)
@ResponseBody
public void getUrlFile(String url, HttpServletRequest request, HttpServletResponse response) {
String serverUrl = "D:\\temp-appImg\\";
String imgUrl = serverUrl + url;
File file = new File(imgUrl);
// 后缀名
String suffixName = url.substring(url.lastIndexOf("."));
String imgType = "image/" + suffixName;
//判断文件是否存在如果不存在就返回默认图标
if (!(file.exists() && file.canRead())) {
file = new File(request.getSession().getServletContext().getRealPath("/")
+ "resource/icons/auth/root.png");
}
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
int length = inputStream.read(data);
inputStream.close();
//setContentType("text/plain; charset=utf-8"); 文本
response.setContentType(imgType + ";charset=utf-8");
OutputStream stream = response.getOutputStream();
stream.write(data);
stream.flush();
stream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
更多相关内容 -
pdf.js使用文件流预览pdf
2015-09-27 23:16:40网上大部分pdf.js都是用url方式预览pdf,此处给出pdf.js使用文件流预览pdf的Web工程; 此是maven工程; 100%能运行; -
文件和文件流
2019-08-08 20:16:26文件和文件流 1. File类 Java.io.File类可以获取文件以及文件夹的一些基本的属性 常用的方法 文件名称,路径,大小,判断是否存在,删除,创建 // 创建一个文件对象(可以是文件,可以是文件夹) File file = new ...文件和文件流
1. File类
Java.io.File类可以获取文件以及文件夹的一些基本的属性
常用的方法 文件名称,路径,大小,判断是否存在,删除,创建// 创建一个文件对象(可以是文件,可以是文件夹) File file = new File("e:/java_text.txt"); // 基本属性 boolean canWriter = file.canWrite(); System.out.println("是否可写:" + canWriter); boolean canRead = file.canRead(); System.out.println("是否可读:" + canRead); long size = file.length(); // 常用 System.out.println("文件大小:" + size); boolean isFile = file.isFile(); // 常用 System.out.println("是否是文件:" + isFile); boolean isDirectory = file.isDirectory(); System.out.println("是否是文件夹:" + isDirectory); String filename = file.getName(); // 常用 System.out.println("文件的名称:" + filename); String absolutePath = file.getAbsolutePath(); // 常用 System.out.println("文件的绝对路径:" + absolutePath); String filepath = file.getPath(); System.out.println("文件的绝对路径:" + filepath); boolean isExists = file.exists(); // 常用 System.out.println("是否存在:" + isExists); boolean isDelete = file.delete(); // 常用 System.out.println("是否已经被删除:" + isDelete); boolean isCreate = file.createNewFile(); System.out.println("创建了没有:" + isCreate);
File类的listFile获取文件夹下面的所有文件内容,可以通过递归调用的方法把某一个文件夹下的所有的文件查询出来
// 测试文件目录的属性(递归遍历文件夹中所有的文件信息) public static void testDirectoryDeme(File file) { if (file.isDirectory()) { File[] files = file.listFiles(); System.out.println("文件夹"+file.getName()+"有"+files.length+"个文件"); // 利用for遍历所有的文件 for (int i = 0; i < files.length; i++) { File childFile = files[i]; if (childFile.isFile()) { // 这是一个文件 System.out.println("\t这是一个文件:" + childFile.getName()); } else { // 文件夹:继续递归调用 testDirectoryDeme(childFile); } } } else { // 这是一个文件 System.out.println("\t这是一个文件:" + file.getName()); } }
2. Files 和 paths是一个工具类,提供了对文件的基本功能的实现在java.nio包下面
文件的创建,删除,判断是否存在,移动,拷贝. 因为提供了静态的方法,所以不需要创建对象直接调用方法即可
// 如果文件不存在复制 if (!Files.exists(Paths.get("e:/a/cart1.jpg"))) { // java.nio.Files(文件的工具类) Paths(文件路径工具类) Files.copy(Paths.get("e:/cart1.jpg"), Paths.get("e:/a/cart1.jpg")); } Files.move(Paths.get("e:/a/cart1.jpg"), Paths.get("e:/a/b/cart1" + ((int) (Math.random() * 100)) + ".jpg")); Files.delete(Paths.get("e:/cart1.jpg"));
3. 文件流
文件流的分类:
根据功能分为:输入流(读取文件) 和 输出流(写入文件)
根据操作内容:字符流(读取字符数组) 和 字节流(读取字节数组)
字节输入流,字节输出流,字符输入流,字符输出流
使用字节流实现文件的读取//利用字节输入流实现文件的内容读取(inputStream 接口的 FileInputStream ) public static void testInputStream() throws Exception{ File file = new File("e:/a/file.txt"); InputStream is = new FileInputStream(file); if(!file.exists()){ System.out.println("文件不存在"); } //开始读取文件 byte[] temp_bytes = new byte[1024]; int size = 0; //用于记录读取文件的字节个数,如果没有读取任何的内容返回-1 //因为文件不可能一次读取完毕,需要循环读取 do{ size =is.read(temp_bytes); if(size!=-1){ String info = new String(temp_bytes,0,size,"GBK"); System.out.println("读取的内容是:" + info); } }while(size !=-1); //文件流是必须要关闭的(像水管子一样) is.close();
利用字节输出流实现文件的写入
//利用字节输出流实现文件内容的写入(OutputStream 接口的FileOutputStream) public static void testOuputStream() throws Exception{ File file = new File("e:/a/file_new.txt"); if(file.exists()){ file.createNewFile(); } //文件写入 String info = "这就是我们要写入文件的内容"; //创建文件写入对象 OutputStream os = new FileOutputStream(file); os.write(info.getBytes()); //写入完毕后,关闭 os.flush(); //清空缓存区 os.close(); }
利用字节输入流和字节输出流实现文件的拷贝
//利用字节输入输入输出流,实现文件的复制,为了防止文件名称重复,需要对文件名称重命名 public static void testCopy(String filepath) throws Exception { //创建文件对象 File file = new File(filepath); //判断文件是否存在,且必须是一个文件而不能是一个文件夹 if(!file.exists()) throw new Exception("文件不存在"); if(file.isDirectory()) throw new Exception("只能拷贝文件,不能拷贝文件夹"); //默认目标地址就是e:/a 文件夹 //开始拷贝 //创建一个文件输入流对象,读取文件的内容 InputStream is = new FileInputStream(file); //创建一个文件输出流对象,写入文件的内容 String filename = getFileName(file.getName()); String targetpath="e:/a/"+filename; OutputStream os = new FileOutputStream(targetpath); //利用循环,边读取内容,边写入内容即可 byte[] temp_info = new byte[1024]; //利用临时数组保存读取的内容 int size = 0; //保存读取的字节个数,如果没有读取到内容返回-1 do{ //先读取 size = is.read(temp_info); //判断是否读取到了文件的内容 if(size!=-1){ //写入文件 os.write(temp_info, 0, size); } }while(size!=-1); //关闭,先关闭输出流,后关闭输入流 os.flush(); os.close(); is.close(); } //根据原有的文件名称获取新的文件名称 public static String getFileName(String fileName){ SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss"); //abc.mp4 ---abc_20190805164520.mp4 //根据.分别获取文件名称和扩展名 String[] name_infos = fileName.split("\\."); //获取当前日期的字符串 Date date = new Date(); String dateStr = sdf.format(date); return name_infos[0]+"_"+dateStr+"."+name_infos[1]; }
重点是熟练使用FileInputStream 和FileOutputStream 的使用
// 利用字节流复制某一个文件夹中的所有文件 public static void testCopyDirectory() throws Exception { File file = new File("e:/file_source"); // 实现复制 // 创建文件输入输出流对象 InputStream is = null; OutputStream os = null; try { // 遍历这个文件夹下的所有的文件信息 File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { File childFile = files[i]; // 如果是一个文件就复制 if (childFile.isFile()) { is = new FileInputStream(childFile); // 根据原有的文件名称获取新的文件名称 String newFileName = getNewFileName(childFile.getName()); os = new FileOutputStream("e:/a/b/" + newFileName); byte[] temp_info = new byte[1024]; int size = -1; do { // 先读取 size = is.read(temp_info); // 后写入(写入的内容多去取决于读取的内容多少) if (size != -1) { os.write(temp_info, 0, size); } } while (size != -1); } } } catch (Exception ex) { throw new Exception(ex); } finally { if (os != null) os.close(); if (is != null) is.close(); } } // 根据原有的文件名称,获取新的文件名称 public static String getNewFileName(String oldFileName) { // oldname :上机作业.docx newnmae : 上机作业_20180222.docx; // 根据原有的文件名称获取文件名字和文件的类型 int index = oldFileName.lastIndexOf("."); if (index == -1) { return oldFileName; } // 获取文件名: 上机作业 String name = oldFileName.substring(0, index); // 获取文件类型: docx String type = oldFileName.substring(index + 1); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss"); Date date = new Date(); String formatstr = sdf.format(date); // 上机作业_20180222.docx; return name + "_" + formatstr + "." + type; }
使用对象输入输出流实现对象的序列化和反序列化
public static void testObjectInputStream() throws Exception{ File file = new File("e:/a/stu.txt"); InputStream is = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(is); List<Student> stuList= (List<Student>)ois.readObject(); ois.close(); is.close(); for(Student stu: stuList){ System.out.println(stu); } } //对象序列化(实现JAVA对象的保存和读取 ObjectInputStream) public static void testObjectOutputStream() throws Exception{ Student stu3 = new Student("赵丽丽","女","河北廊坊"); stuList.add(stu3); //把集合保存到文件中 File file = new File("e:/a/stu.txt"); OutputStream os = new FileOutputStream(file); ObjectOutputStream oos = new ObjectOutputStream(os); oos.writeObject(stuList); oos.flush(); oos.close(); os.close(); }
字符流的读取和写入(只能读取字符文件的信息)
//使用字符流读取文件 public static void testReader() throws Exception{ //创建文件对象 File file = new File("e:/a/file.txt"); //创建字符输入流对象 Reader reader = new FileReader(file); //创建字符输出流对象 File file2 = new File("e:/a/b/file_3.txt"); Writer writer = new FileWriter(file2); char[] temp = new char[1000]; int size =0; //通过循环边度编写 do{ size= reader.read(temp); //读取字符内容 if(size!=-1) { writer.write(temp, 0, size); } }while(size!=-1); //关闭 writer.flush(); writer.close(); reader.close(); }
释放资源的新方法
//新的关闭资源的方法 //try( 定义必须要关闭的对象; ){}catch(Exception ex){}; // 创建输出流对象 try( OutputStream os = new FileOutputStream(FILE_PATH); ObjectOutputStream oos = new ObjectOutputStream(os); ) { oos.writeObject(stuList); } catch (Exception e) { throw new Exception(e); }
4. 线程的状态
初始状态(创建了对象)
可运行状态(调用了start方法)
运行状态(调用了run方法)
阻塞状态 (调用了seleep,join,wait方法)
终结状态 (运行完毕)
5. 线程的常用方法
Start() 启动方法 表示线程进入了可运行状态
Seleep(int) 随眠方法,当前线程进入阻塞状态,在一定时间以后苏醒
Join() 方法 被调用者优先执行,执行完毕后当前线程在执行(阻塞的的是当前线程)
Wait() 方法 当前线程进入阻塞状态,一直到对方唤醒自己才可以继续执行
notifyAll()唤醒被阻塞的线程
需要注意:wait(),notify()两个方法是Object类提供的package com.xja.sxnd.filedemo; public class ThreadDemo { public static void main(String[] args) { MyThread mt = new MyThread(); MyRunable mr = new MyRunable(); Thread thread = new Thread(mr); mt.start(); thread.start(); for(int i = 0;i< 50;i++){ if(i == 20){ try{ //主线程执行到20的时候,先让第一个线程执行完毕,然后主线程在接着执行 mt.join(); }catch(Exception ex){ ex.printStackTrace(); } } System.out.println("主线程中的内容:" +i); } } } class MyThread extends Thread { @Override public void run() { for(int i =0;i< 50;i++){ try{ if(i==20) Thread.sleep(500); //停止运行0.5秒,时间到了以后自动执行 }catch(Exception ex){ ex.printStackTrace(); } System.out.println("第一个线程的对象:" +i); } } } class MyRunable implements Runnable{ @Override public void run() { for(int i =0;i< 50;i++){ System.out.println("第二个线程的对象:"+i); } } }
.
6. 线程的死锁
如果两个线程同时调用对方线程的JOIN方法,互相希望对方先运行就会出现死锁的问题
public class MyRunnable implements Runnable { public Thread myThread; @Override public void run() { try { for (int i = 0; i < 100; i++) { Thread.sleep(10); if(i == 5){ System.out.println("MyRunnable运行到了5,也休息,让Thread先走"); myThread.join(); } System.out.println("第二个线程:" + i); } } catch (InterruptedException e) { e.printStackTrace(); } } } public class MyThread extends Thread { public Thread myRun; @Override public void run() { try { for (int i = 0; i < 10; i++) { Thread.sleep(10); if(i==5){ System.out.println("Thread 运行到了5 就需要对方先走"); myRun.join(); } System.out.println("第一个线程的内容:" + i); } } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { // TODO Auto-generated method stub try { // 创建一个线程对象 MyThread myThread = new MyThread(); // 创建第二个线程 MyRunnable myRunn = new MyRunnable(); Thread thread = new Thread(myRunn); // 启动线程 启动线程不能直接调用run 只能调用start myThread.myRun = thread; myRunn.myThread = myThread; myThread.start(); thread.start(); }
7. 线程的同步
StringBuilder和StringBuffer ArrayList 和vector HashMap 和HashTable
当两个线程同时操作同一个对象的时候,因为两个线程互相影响对方的结果,导致数据不统一,这种现象称之为线程不同步
例如:银行卡存取钱的问题。(两种方式操作一个账户)public class Card { private int balance =500; public void takeMoney(int money){ if(balance>money){ System.out.println("取钱之前的余额:" + balance); int temp_balance = balance - money; balance = temp_balance; System.out.println("取钱之后的余额:" + balance); } } public void saveMoney(int money){ System.out.println("存钱之前的余额:" + balance); int temp_balance = balance + money; balance = temp_balance; System.out.println("存钱之后的余额:" + balance); } } public class ThreadDemo { public static void main(String[] args) { Card card = new Card(); MyThread mt = new MyThread(card); MyRunable mr = new MyRunable(card); Thread thread = new Thread(mr); mt.start(); thread.start(); System.out.println("程序结束"); } } class MyThread extends Thread { private Card card; public MyThread(Card card){ this.card = card; } @Override public void run() { for(int i =0;i< 10;i++){ card.takeMoney(50); } } } class MyRunable implements Runnable{ private Card card; public MyRunable(Card card){ this.card = card; } @Override public void run() { for(int i =0;i< 10;i++){ card.saveMoney(50); } } }
通过synchronized关键字修饰方法就是线程同步的方法,线程同步的方法要求同一个对象同时只能调用一个方法
public class Card { private int balance = 500; public void takeMoney(int money) { synchronized (this) { if (balance > money) { System.out.println("取钱之前的余额:" + balance); int temp_balance = balance - money; balance = temp_balance; System.out.println("取钱之后的余额:" + balance); } } } public void saveMoney(int money) { synchronized (this) { System.out.println("存钱之前的余额:" + balance); int temp_balance = balance + money; balance = temp_balance; System.out.println("存钱之后的余额:" + balance); } } }
8. 线程的经典案例(生产者和消费者)
public class Card { private int balance = 500; public synchronized void takeMoney(int money) throws Exception { if (balance -money<0) { System.out.println("家里没有钱了,需要减少消费"); this.wait(); return; } System.out.println("取钱之前的余额:" + balance); int temp_balance = balance - money; balance = temp_balance; System.out.println("取钱之后的余额:" + balance); // 一旦我花费了钱,就可以让生成者继续生成 this.notify(); } public synchronized void saveMoney(int money) throws Exception { // 如果挣钱的足够,则需要休息,让消费者消费 if (balance > 700) { System.out.println("钱以够多了,可以休息一下"); this.wait(); return; } System.out.println("存钱之前的余额:" + balance); int temp_balance = balance + money; balance = temp_balance; System.out.println("存钱之后的余额:" + balance); // 一旦有钱就可以让消费者消费 this.notifyAll(); } }
-
vue 接收后端文件流 并下载
2021-11-09 16:37:49在vue框架中, 接收并下载文件流(blob对象) 可以通过将其转成blob对象,添加到a标签或者iframe标签中来模拟下载(或者pdf预览) 1.首先设置responseType对象格式为 blob: responseType:‘blob’ 在项目reques....在vue框架中, 接收并下载文件流(blob对象)
可以通过将其转成blob对象,添加到a标签或者iframe标签中来模拟下载(或者pdf预览)1.首先设置responseType对象格式为 blob:
responseType:‘blob’在项目reques.js文件中 添加请求头的相关配置 如header responseType 等 config.headers['Authorization'] = getToken() if(config.responseType){ config.responseType = 'blob' }
在api.js文件中 添加responseType:'blob'参数 //授权码下载 export function downloadcode(query) { return request({ url: '/authCode/download', method: 'get', params: query, responseType:'blob' }) }
项目页面中: //下载方法 handleDown(row) { const data = { id:row.id } downloadcode(data).then(res => { console.log("下载的文件流",res) const link=document.createElement('a'); try{ // let blob = new Blob([res.data],{type: 'application/vnd.ms-excel'}); //如果后台返回的不是blob对象类型,先定义成blob对象格式 let blob = res.data //如果后台返回的直接是blob对象类型,直接获取数据 let _fileName = res.headers['content-disposition'].split(';')[1].split('=')[1]; //拆解获取文件名, link.style.display='none'; 方法1: 创建--下载--销毁 // 兼容不同浏览器的URL对象 const url = window.URL || window.webkitURL || window.moxURL; link.href=url.createObjectURL(blob); link.download = _fileName; //下载的文件名称 link.click(); window.URL.revokeObjectURL(url); // #URL.revokeObjectURL()方法会释放一个通过URL.createObjectURL()创建的对象URL. 当你要已经用过了这个对象URL,然后要让浏览器知道这个URL已经不再需要指向对应的文件的时候,就需要调用这个方法. 方法2: 创建--下载--销毁 // 兼容不同浏览器的URL对象 const url = window.URL || window.webkitURL || window.moxURL; link.href=url.createObjectURL(blob); link.setAttribute('download'_fileName.substring(_fileName.lastIndexOf('_')+1))); document.body.appendChild(link); link.click(); document.body.removeChild(link); url.revokeObjectURL(link.href);//销毁url对象 }catch (e) { console.log('下载的文件出错',e) } }) },
返回的文件流 示例:
axios get 请求方式
axios.get(`/dev-api/authCode/download?id=`+row.id, { //请求头需要的一些配置 headers:{ "Authorization":getToken() }, responseType: 'blob',//设置返回类型 } ).then((res)=>{ console.log('下载的文件',res) const link=document.createElement('a'); try{ let blob = res.data let _fileName = res.headers['content-disposition'].split(';')[1].split('=')[1];//文件名,中文无法解析的时候会显示 _(下划线),生产环境获取不到 link.style.display='none'; // 兼容不同浏览器的URL对象 const url = window.URL || window.webkitURL || window.moxURL; link.href=url.createObjectURL(blob); link.download = _fileName; link.click(); window.URL.revokeObjectURL(url); }catch (e) { console.log('下载的文件出错',e) } }).catch(()=>{ console.log('下载的文件出错') })
参考:https://www.cnblogs.com/raymond-yan/p/10364120.html
https://blog.csdn.net/clmmei_123/article/details/108105046 -
C++ 文件流详解
2020-02-05 14:20:31C++使用流进行操作文件前言:
我们刚开始学习C 时,都是使用iostream里面的cin和cout进行控制台的输入和输出,现在我们学习如何从文件读取流和向文件写入流。IO: 向设备输入数据和输出数据
C 的IO流:
设备:
- 文件
- 控制台
- 特定的数据类型(stringstream)
c 中,必须通过特定的已经定义好的类, 来处理IO(输入输出)
欲要使用文件流,这就需要用到 C 中的标准库 #include < fstream >,它定义了三个数据类型:
ofstream:该数据类型表示输出文件流,用于创建文件并向文件写入信息。
ifstream:该数据类型表示输入文件流,用于从文件读取信息。
fstream:该数据类型表示输入和输出文件流,且同时具有 ofstream 和 ifstream 两种功能,这意味着它可以创建文件,向文件写入信息,从文件读取信息。
定义文件流
想要使用文件流对文件进行操作,修必须要先定义它。
定义时须包含头文件#include< fstream >三种定义方法:
#include <fstream> using namespace std; // 声明命名空间 int main(void) { // 1》 // 声明输出文件流,用于创建文件并向文件写入信息。 ofstream outFile; // 2》 // 声明输入文件流,用于从文件读取信息。 ifstream inFIle; // 3》 // 声明输入和输出文件流,且同时具有 ofstream 和 ifstream 两种功能,这意味着它可以创建文件,向文件写入信息,从文件读取信息。 fstream stream; return 0; }
打开文件
在从文件读取信息或者向文件写入信息之前,必须先打开文件。ofstream 和fstream 对象都可以用来打开文件进行写操作,如果只需要打开文件进行读操作,则使用 ifstream 和 fstream对象。
打开文件的方法:
使用open()函数进行文件的打开#include < fstream >
void open( const char *filename );例1:ofstream打开文件的方式(写数据进文件中)
ofstream outFile; outFile.open("demo.txt"); // 默认方式打开文件
例2:ifstream打开文件的方式(读取文件中的数据)
ifstream inFile; inFile.open("demo.txt"); // 默认当方式打开文件
例3: fstream打开文件的方式(读写文件中的数据)
fstream stream stream.open("demo.txt"); // 默认方式打开文件
文件的打开方式
模式标志 描述 ios::in 读方式打开文件 ios::out 写方式打开文件 ios::trunc 如果此文件已经存在, 就会打开文件之前把文件长度截断为0 ios::app 尾部最加方式(在尾部写入) ios::ate 文件打开后, 定位到文件尾 ios::binary 二进制方式(默认是文本方式) 以上打开方式, 可以使用位操作 | 组合起来
例:
如果你只是想对文件进行写入操作,当文件已经存在时,你希望对该文件进行截断操作,那么就可这样组合:fstream stream; stream.open("demo.txt", ios::out | ios::trunc);
如果你只是想对文件进行读取操作,而且想在文件尾部读取,那么就可以这样组合:
fstrem inFile; inFile.open("demo.txt", ios::in | ios::ate);
判断文件是否打开成功
使用is_open()函数进行文件的判断
当成功打开文件返回真(true),失败返回假(false)例:
fstream stream; stream.open("demo.txt"); // 判断文件是否打开成功 if (!stream.is_open()) { cout << "文件打开失败!" << endl; system("pause"); exit(-1); }
关闭文件
使用close()函数进行关闭文件
函数的作用是:关闭相关的文件流。例:
// 定义文件流 fstream stream; // 打开文件 stream.open("demo.txt"); // 关闭文件 stream.close(); ///
我们要养成好习惯,打开文件后,一定义要关闭文件再结束程序。
写文件
在C 中,写文件除了要用到ofstream 或者 fstream 外,我们还需要用到一个流插入运算符(<<)。
例:
需求:
让用户来输入姓名和年龄,并保存到文件中。
直到用户输入ctrl z/* 需求: 让用户来输入姓名和年龄,并保存到文件中。 直到用户输入ctrl z */ #include <iostream> #include <Windows.h> #include <string> #include <fstream> // 写文件 using namespace std; int main1(void) { string name; int age; ofstream outfile; // 定义写文件流 // 打开文件 outfile.open("text.txt", ios::out | ios::trunc); if (!outfile.is_open()) { // 判断文件是否打开失败 cout << "文件打开失败!" << endl; system("pause"); exit(-1); } while (1) { cout << "请输入姓名:"; cin >> name; if (cin.eof()) { break; } // ******************************* outfile << name << "\t"; // 将从键盘读取的数据写入文件中 // ******************************* cout << "请输入年龄:"; cin >> age; // 将从键盘读取的数据写入文件中 outfile << age << endl; // 可以连环写入文件 // outfile << name << "\t" << age << endl; } // 关闭文件 outfile.close(); system("pause"); return 0; }
运行截图:
读文件
在C 中,读文件除了要用到ifstream 或者 fstream 外,我们还需要用到一个流插入运算符(>>)。
例:
需求:
在上一个写入文件的例子中,把它写入的text.txt文件中的所有内容都读取出来,并打印出来。#include <iostream> #include <Windows.h> #include <string> #include <fstream> // 读文件 using namespace std; int main(void) { ifstream inFile; string name; int age; // 打开文件 inFile.open("text.txt"); if (!inFile.is_open()) { // 判断文件是否打开失败 cout << "文件打开失败!" << endl; system("pause"); exit(-1); } while (1) { // 从文件中读取第一个数据,并将其打印出来 inFile >> name; if (inFile.eof()) { break; } cout << name << "\t"; // 从文件读取第二数据,并将其打印出来 inFile >> age; cout << age << endl; } system("pause"); inFile.close(); return 0; }
运行截图:
读取文件中的一行数据
使用getline()可以读取文件中的一行数据
例:
stream inFile; string line; inFile("text.txt"); // 从文件中读取一行数据,并将读取到的数据写入字符串变量line中 getline(inFile, line);
总结:
好了,这就是文件的基本用法,C 文件并不难,只要理解好,读取文件要用到搞混文件流,写入文件要用到哪个文件流;需要用到什么方式打开文件等等。不要搞混。
-
react前端下载后端返回文件流(文件流下载excel、csv)
2021-03-08 16:32:35下载excel 文件流下载 -
post提交,图片以文件流形式上传并保存到数据库
2012-09-11 17:59:28post提交,图片以文件流形式上传并保存到数据库,读取的时候再以文件流的形式读取并显示在前端页面 -
[工作笔记]PostMan处理文件流,上传和下载文件流
2020-12-08 16:08:22PostMan处理文件流,上传和下载文件流 一.遇到的问题 postman 进行call api的时候,如果得到的是文件,将会出现一堆乱码 二.解决方案 这时候可以直接下载 在返回body的右上角下载保存就行 也可以在call api的时候就... -
文件流详解:
2019-08-31 16:20:29文件流详解: 低级流: FileOutputStream fos = new FileOutputStream("fos.txt",true); String str = "回首~掏~轨道一开~看不见"; fos.write(str.getBytes("GBK")); `FileInputStream fir = new ... -
使用postman测试上传文件接口,使用文件流的形式
2022-02-15 13:22:431.将headers配置中,Content-Type配置为multipart/form-data 2.根据接口的实际情况配置参数,我的是form-data 3.Body中的文件参数名称配置为file ,类型选择file,选择文件 运行结果 -
Java 安全 后端返回文件流
2021-12-28 17:01:091,起由 业务流程:上传文件——...根据请求执行后端的代码(代码逻辑:根据路径读取文件,输出文件流,响应给前端) 3,配置文件 配置上存文件的保存路径 4,代码: import org.apache.commons.io.IOUtils; @Va -
Vue 前端显示文件流图片
2020-08-07 15:17:53通过前端vue发送用户图片,后端flask进行处理后返回以文件流形式的图片。 前端代码 <template> <v-container> // 注意一个vue文件中只能有一个lable,否则npm run serve 会卡死 <input class=... -
后台接口返回文件流前端实现文件下载
2021-11-18 13:51:06前因:传参后发起post请求,后台接口返回的是二进制文件流,接收的内容如图: 后果:将接收到的文件流直接下载并保存到本地。 要下载的文件是一个.zip 压缩包。 按一般方式请求后台接口,打印接口返回的内容: ... -
前端文件流下载
2020-12-23 15:27:47一、在vux中使用了 Axios 后,后端返回来的是文件流 这里我们可以直接用 Axios 方法返回的 res 赋值到 blob const blob = res const reader = new FileReader() reader.readAsDataURL(blob) reader.onload = ... -
vue实现下载文件流完整前后端代码
2020-12-30 10:37:00使用Vue时,我们前端如何处理后端返回的文件流首先后端返回流,这里我把流的动作拿出来了,我很多地方要用/*** 下载单个文件** @param docId*/@GetMapping("/download/{docId}")public void download(@PathVariable... -
js 文件与文件流之间互换
2019-09-17 14:48:10直接看代码 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="ie=edge">...js文件间互换</title> &... -
使用文件流操作文本文件(文件实训)
2020-04-30 07:34:52C 还可以使用文件流的方式操作文件,使用文件流的方式操作文件需要包含头文件,代码如下: #include <fstream> 头文件中定义了三个类:类 fstream、类 ifstream 和类 ofstream。 类 ifstream 实现文件的输入 ... -
Java返回文件流给前端
2022-03-03 17:11:07import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.... -
后端返回二进制文件流,前端如何下载文件
2020-11-10 20:57:20项目中有一个download接口,这个接口直接返回二进制文件流。之前如果下载文件,一般后端传一个加密串过来,然后前端进行解密,拼接成URL再去下载。现在等于直接把文件发给前端,这种情况下怎么下载文件?问了下同事... -
java根据url获取文件流
2021-01-18 17:52:18最近的一个需求需要根据一个mp3的链接获取文件流上传到内部的存储平台, 记录一下获取文件流的代码吧。 pom文件 <dependency> <groupId>org.apache.thrift</groupId> <artifactId>... -
前端Ajax接收文件流,实现下载excel文件并解决乱码问题
2020-11-29 16:23:06后端(express): Access-Control-Expose-... 使用jQuery接收文件流,获取的excel有乱码: 如果是按照如下格式写,就会有乱码问题,按照上面的方法就不会有问题: $.ajax({ ... responseType: 'blob' // 无效 ... }) -
vue element 前端上传文件后 后台传文件流blob对象下载文件
2020-07-24 10:41:54这里写自定义目录标题后台传文件流blob对象前端下载文件问题解决方案,转成bolb对象创建Blob对象创建链接 后台传文件流blob对象前端下载文件 问题 在页面下载文件时,可以根据路径如 a 标签的 href="" ,但是有时将... -
Feign接口获取文件流问题
2019-06-21 15:50:55文件下载 @GetMapping(value = "/v1/files/**/{file_name:.+}") public void downFile(@PathVariable("file_name") String fileName, HttpServletResponse response, HttpServletRequest request) { // Str... -
Java获取zip文件流
2019-11-23 11:04:14项目中经常遇到需要导出压缩文件的情况,需要压缩的数据来源有网络数据、静态资源,常见的导出场景有:操作日志、密钥文件的导出等。...以流的形式传输数据,避免临时文件的生成,完成后关闭流,z... -
Java 获取url地址文件流
2021-09-14 09:29:24/** * 根据url下载文件流 * @param urlStr * @return */ public static InputStream getInputStreamFromUrl(String urlStr) { InputStream inputStream=null; try { //url解码 URL url = new URL(java.net.... -
vue 浏览器保存后端文件流到本地 | 前端文件流下载文件
2020-05-11 14:05:20本次主要分享一下前端如何保存后端返回文件流到本地,是否为vue项目均可。 关键点: axios URL.createObjectURL 实现思路: 首先设置axios的响应类型为 responseType: 'blob' ,也就把流文件转换成blob对象;... -
PDF.JS-文件流方式在线展示pdf文件
2020-09-03 12:19:04目前所在项目要求实现在线预览PDF...下载后解压文件,直接拖进项目里就可以: 一些其博客说要把viewer.js里面的 defaultUrl: { value: "compressed.tracemonkey-pldi-09.pdf", kind: OptionKind.VIEWER ... -
使用EasyExcel返回文件流,导出excel
2021-09-22 16:39:52在j项目开发中经常会有导出文件excel的需求,对此EasyExcel是个非常好用的工具,官方羽雀文档地址https://www.yuque.com/easyexcel/doc/easyexcel,这里简单总结一下使用该工具返回文件流的操作。 1.引入依赖 <... -
js保存文件流
2018-05-10 19:10:52var blob = new Blob([要保存的文件流], { type: 'application/octet-stream' }), fileName = 'filename' + path.substring(path.lastIndexOf("."), path.length); ////filename,摘取了常用的部分,其实还有其他... -
C++输入输出文件流
2020-02-12 20:40:38标准输出流(cout) 预定义的对象 cout 是 iostream 类的一个实例。cout 对象“连接”到标准输出设备,通常是显示屏。cout 是与流插入运算符 << 结合使用的。 标准输入流(cin) 预定义的对象 cin 是 iostream...