package www.cfyg.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.FileWriter; import java.io.IOException; /** * @program: file * @Date: 2019/1/15 10:27 * @Author:懒惰的小妖 * @Description:第一种方案 在aa文件夹下的txt文件中添加"Hello world!" */ @RestController public class FileController { /** * 取得aa文件下的所有文件。 */ @GetMapping("/path") public File[] listFiles(HttpServletRequest request){ //创建file对象,获取本机C盘的aa文件下的文件。 File file = new File("c:/aa"); //这个文件下有文件夹也有txt。 File[] ref = file.listFiles(); //for循环遍历,对得到文件 for (File f:ref){ //txt是一种文本文件 if(f.isFile()){ FileWriter writer=null; try { writer=new FileWriter(f,true); writer.write("Hello world!"); } catch (IOException e) { e.printStackTrace(); }finally { if(writer!=null) { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } } } return ref; } }
package www.zfj.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import java.io.*; /** * @program: file * @Date: 2019/1/15 10:27 * @Author:懒惰的小妖 * @Description:第二种方案 在aa文件夹下的txt文件中添加"Hello world!" */ @RestController public class FileController { @GetMapping("/path") public File[] listFiles(HttpServletRequest request) throws IOException{ //创建file对象,获取本机C盘的aa文件下的文件。 File file = new File("c:/aa"); //这个文件下有文件也有其他。 File[] ref = file.listFiles(); //for循环遍历,对得到文件 for (File f:ref){ //txt是一种文本文件 if(f.isFile()){ RandomAccessFile raf= null; try { raf = new RandomAccessFile(f,"rw"); //设置文件指针偏移,从该文件的开头测量,发生下一次读取或写入。 偏移可以设置为超出文件的末尾。 设置超出文件末尾的偏移量不会更改文件长度。 文件长度只有在偏移设置超出文件结尾之后才会通过写入进行更改。 raf.seek(8); //writeByte()将字符串作为字节序列写入文件 raf.writeBytes("Hello world!"); } catch (FileNotFoundException e) { e.printStackTrace(); }finally { if(raf!=null) { try { raf.close(); } catch (IOException e) { e.printStackTrace(); } } } } } return ref; } }
打开txt文件都追加上:"Hello world!".