方式一:
import java. io. File ;
import java. io. FileWriter ;
import java. io. IOException ; public class WriterFileUtils { private static final String prefix = "classpath:" ; public static void writeFile ( String directory, String fileName, String content) { directory = prefix + directory; try { File dir = new File ( directory) ; if ( ! dir. exists ( ) ) { dir. mkdir ( ) ; } String filePath = directory + fileName; File file = new File ( filePath) ; if ( ! file. exists ( ) ) { file. createNewFile ( ) ; } FileWriter fw = new FileWriter ( filePath) ; fw. write ( content) ; fw. close ( ) ; } catch ( IOException e) { throw new RuntimeException ( e) ; } } }
方式二:
import java. io. File ;
import java. io. FileWriter ;
import java. io. IOException ; import org. springframework. beans. factory. annotation. Autowired ;
import org. springframework. core. io. Resource ;
import org. springframework. core. io. ResourceLoader ;
public class WriterFileUtils { public static final WriterFileUtils INSTANCE = new WriterFileUtils ( ) ; @Autowired private ResourceLoader resourceLoader; private static final String prefix = "classpath:" ; public void writeFile ( String directory, String fileName, String content) { try { directory = prefix + directory; Resource dirResource = resourceLoader. getResource ( directory) ; File dir = dirResource. getFile ( ) ; if ( ! dir. exists ( ) ) { dir. mkdir ( ) ; } String filePath = directory + fileName; Resource fileResource = resourceLoader. getResource ( filePath) ; File file = fileResource. getFile ( ) ; if ( ! file. exists ( ) ) { file. createNewFile ( ) ; } FileWriter fw = new FileWriter ( filePath) ; fw. write ( content) ; fw. close ( ) ; } catch ( IOException e) { throw new RuntimeException ( e) ; } } }