IO Streams Get Input Stream from filepath
String filepath = "D:\\test.txt" InputStream is = new FileInputStream (filepath);Path path = Paths.get(filepath); System.out.println(path.normalize().toUri().toString()); InputStream is = new URL (path.toUri().toString()).openStream();
Get Input Stream from classpath
InputStream resourceAsStream = new ClassPathResource ("application.yml" ).getInputStream();InputStream resourceAsStream = new ClassPathResource ("/application.yml" ).getInputStream();InputStream resourceAsStream = <CurrentClass>.class.getResourceAsStream("/application.yml" );InputStream resourceAsStream = <CurrentClass>.class.getClassLoader().getResourceAsStream("application.yml" );
Get Input Stream from file HTTP URL
InputStream input = new URL ("http://xxx.xxx/fileUri" ).openStream();URLConnection connection = new URL (url + "?" + query).openConnection();connection.setRequestProperty("Accept-Charset" , charset); InputStream response = connection.getInputStream();HttpResponse response = HttpRequest .create(new URI ("http://xxx.xxx/fileUri" )) .headers("Foo" , "foovalue" , "Bar" , "barvalue" ) .GET() .response(); Resource resource = new UrlResource ("http://xxx.xxx/fileUri" );InputStream is = resource.getInputStream();
Using Stream API (Java 8)
new BufferedReader (new InputStreamReader (in)).lines().collect(Collectors.joining("\n" ))
Using IOUtils.toString
(Apache Commons IO API)
String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
Using ByteArrayOutputStream
and inputStream.read
(JDK)
ByteArrayOutputStream result = new ByteArrayOutputStream ();byte [] buffer = new byte [1024 ];for (int length; (length = inputStream.read(buffer)) != -1 ; ) { result.write(buffer, 0 , length); } return result.toString("UTF-8" );
Performance: ByteArrayOutputStream > IOUtils.toString > Stream API
Output Streams Write data to file Write string to file
String s = "hello world" ;String outputFilePath = new StringBuilder () .append(System.getProperty("java.io.tmpdir" )) .append(UUID.randomUUID()) .append(".txt" ) .toString(); try (BufferedOutputStream out = new BufferedOutputStream (new FileOutputStream (outputFilePath))) { out.write(s.getBytes(StandardCharsets.UTF_8)); } System.out.println("output file path: " + outputFilePath);
Read and write Read From and Write to Files Java IO
String inputFilePath = new StringBuilder () .append(System.getProperty("java.io.tmpdir" )) .append("7d43f2b6-2145-4448-9c8f-c43f97ba4d9e.txt" ) .toString(); String outputFilePath = new StringBuilder () .append(System.getProperty("java.io.tmpdir" )) .append(UUID.randomUUID()) .append(".txt" ) .toString(); try (BufferedInputStream in = new BufferedInputStream (new FileInputStream (inputFilePath)); BufferedOutputStream out = new BufferedOutputStream (new FileOutputStream (outputFilePath))) { int b; while ((b = in.read()) != -1 ) { out.write(b); } } System.out.println("output file path: " + outputFilePath);
For read and write, you can use the following two ways:
int b;while ((b = in.read()) != -1 ) { out.write(b); }
or
byte [] buffer = new byte [1024 ];int lengthRead;while ((lengthRead = in.read(buffer)) > 0 ) { out.write(buffer, 0 , lengthRead); out.flush(); }
Java NIO.2 API
String inputFilePath = new StringBuilder () .append(System.getProperty("java.io.tmpdir" )) .append("7d43f2b6-2145-4448-9c8f-c43f97ba4d9e.txt" ) .toString(); String outputFilePath = new StringBuilder () .append(System.getProperty("java.io.tmpdir" )) .append(UUID.randomUUID()) .append(".txt" ) .toString(); Path originalPath = new File (inputFilePath).toPath();Path copied = Paths.get(outputFilePath);Files.copy(originalPath, copied, StandardCopyOption.REPLACE_EXISTING); System.out.println("output file path: " + outputFilePath);
Get a Path object by Paths.get(filePath)
or new File(filePath).toPath()
By default, copying files and directories won’t overwrite existing ones, nor will it copy file attributes.
This behavior can be changed using the following copy options:
REPLACE_EXISTING – replace a file if it exists
COPY_ATTRIBUTES – copy metadata to the new file
NOFOLLOW_LINKS – shouldn’t follow symbolic links
Apache Commons IO API
FileUtils.copyFile(original, copied);
Files Get File Path get file path by class path
String filePath = new ClassPathResource (fileClassPath).getFile().getAbsolutePath();URL url = FileUtils.class.getClassLoader() .getResource(fileClassPath); String filePath = Paths.get(url.toURI()).toFile().getAbsolutePath();
Creation Create directory
File dir = new File (dirPath);if (!dir.exists() || !dir.isDirectory()) { dir.mkdirs(); }
Files.createDirectories(new File (outputDir).toPath());
Delete Delete a file
File file = new File (filePath);file.delete(); file.deleteOnExit();
Delete a directory
Java API
public static void deleteDirectory (File file) { for (File subfile : file.listFiles()) { if (subfile.isDirectory()) { deleteDirectory(subfile); } subfile.delete(); } }
Apache Common IO API
FileUtils.deleteDirectory(new File (dir));
or
FileUtils.forceDelete(new File (dir));
Update Traversal Java File Mime Type
String mimeType = Files.probeContentType(file.toPath());String mimeType = URLConnection.guessContentTypeFromName(fileName);FileNameMap fileNameMap = URLConnection.getFileNameMap();String mimeType = fileNameMap.getContentTypeFor(file.getName());MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap ();String mimeType = fileTypeMap.getContentType(file.getName());
Temporary Files and Directories Temporary Directory
System.getProperty("java.io.tmpdir" )
Windows 10: C:\Users\{user}\AppData\Local\Temp\
Debian: /tmp
Temporary file
File file = File.createTempFile("temp" , null );System.out.println(file.getAbsolutePath()); file.deleteOnExit();
Path path = Files.createTempFile(fileName, ".txt" );System.out.println(path.toString());
Problems Character Encoding Problems The one-arguments constructors of FileReader always use the platform default encoding which is generally a bad idea.
Since Java 11 FileReader has also gained constructors that accept an encoding: new FileReader(file, charset) and new FileReader(fileName, charset).
In earlier versions of java, you need to use new InputStreamReader(new FileInputStream(pathToFile), ).
References