InputStream is = new FileInputStream("D:\\My Desktop\\test.txt");
org.springframework.core.io.UrlResource
Spring framework Resource Interface
Java’s standard java.net.URL class and standard handlers for various URL prefixes unfortunately are not quite adequate enough for all access to low-level resources. For example, there is no standardized URL implementation that may be used to access a resource that needs to be obtained from the classpath, or relative to a ServletContext. While it is possible to register new handlers for specialized URL prefixes (similar to existing handlers for prefixes such as http:), this is generally quite complicated, and the URL interface still lacks some desirable functionality, such as a method to check for the existence of the resource being pointed to.
1 2 3 4 5
String filepath = "D:\\My Desktop\\test.txt"; Path path = Paths.get(filepath).normalize(); //path.toUri().toString(): file:///D:/My%20Desktop/test.txt Resource resource = new UrlResource(path.toUri()); InputStream is = resource.getInputStream();
java.net.URL
1 2 3 4
String filepath = "D:\\My Desktop\\test.txt"; Path path = Paths.get(filepath).normalize(); //path.toUri().toString(): file:///D:/My%20Desktop/test.txt InputStream is = new URL(path.toUri().toString()).openStream();
Read data from Java classpath
org.springframework.core.io.ClassPathResource
1 2 3
// src/main/resources/application.yml Resource resource = new ClassPathResource("application.yml"); InputStream is = resource.getInputStream();
org.springframework.core.io.ResourceLoader
1 2 3 4 5
@Autowired ResourceLoader resourceLoader;
resourceLoader.getResource("classpath:application.yml"); InputStream is = resource.getInputStream();
Read data from memory
1 2
byte[] data = new String("data...").getBytes(StandardCharsets.UTF_8); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
Read data From HTTP URL
java.net.URL
1
InputStream is = new URL("http://demo.com/test.txt").openStream();
org.springframework.core.io.UrlResource
1 2
Resource resource = new UrlResource("http://demo.com/test.txt"); InputStream is = resource.getInputStream();
java.net.HttpURLConnection
1 2 3
URLConnection urlConnection = new URL("http://demo.com/test.txt").openConnection(); urlConnection.connect(); InputStream is = urlConnection.getInputStream();
Read data from OSS
Reference my another post: Common OSS Java SDK Usage
Write
Write data to disk
1 2 3 4 5 6 7 8 9 10 11 12 13 14
byte[] data = new String("data").getBytes(StandardCharsets.UTF_8); String storeFilePath = "D:/My Workspace/test/test.txt"; try ( ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data); FileOutputStream fileOutputStream = new FileOutputStream(storeFilePath) ) { byte[] buf = newbyte[1024]; int len = 0; while ((len = byteArrayInputStream.read(buf)) != -1) { fileOutputStream.write(buf, 0, len); } } catch (IOException e) { e.printStackTrace(); }
Write data to memory
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
byte[] data = new String("data").getBytes(StandardCharsets.UTF_8); byte[] storeDataArray; try ( ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ) { byte[] buf = newbyte[1024]; int len = 0; while ((len = byteArrayInputStream.read(buf)) != -1) { byteArrayOutputStream.write(buf, 0, len); } storeDataArray = byteArrayOutputStream.toByteArray(); System.out.println(new String(storeDataArray, StandardCharsets.UTF_8)); } catch (IOException e) { e.printStackTrace(); }
Write data to OSS
Reference my another post: Common OSS Java SDK Usage
Print txt file to console
stream
1 2
InputStream is = new FileInputStream("D:\\My Desktop\\test.txt"); new BufferedReader(new InputStreamReader(is)).lines().forEach(System.out::println);
try ( FileOutputStream fileOutputStream = new FileOutputStream("D:/My Workspace/test/test.zip"); ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream) ) { int fileNumber = 3; for (int i = 1; i <= fileNumber; i++) { String childFilename = "file" + i + ".zip"; zipOutputStream.putNextEntry(new ZipEntry(childFilename)); try ( ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ZipOutputStream nestedZipOutputStream = new ZipOutputStream(byteArrayOutputStream); ) { int nestedNumber = 3; for (int j = 1; j <= nestedNumber; j++) { String nestedFileName = new StringBuilder() .append("file").append(i) .append("nestFile").append(j) .append(".txt").toString(); nestedZipOutputStream.putNextEntry(new ZipEntry(nestedFileName)); nestedZipOutputStream.write(("nest file" + j).getBytes(StandardCharsets.UTF_8)); nestedZipOutputStream.closeEntry(); } nestedZipOutputStream.finish(); zipOutputStream.write(byteArrayOutputStream.toByteArray()); } zipOutputStream.closeEntry(); } zipOutputStream.finish(); } catch (IOException e) { e.printStackTrace(); }
Speed up read or write
Using buffer to decrease calls to the underlying runtime system
Direct Buffering
1 2 3 4 5 6 7 8 9 10 11 12 13 14
String inputFilePath = "C:\\Users\\Taogen\\Desktop\\input.txt"; String outputFilePath = "C:\\Users\\Taogen\\Desktop\\output.txt"; try ( FileInputStream fileInputStream = new FileInputStream(inputFilePath); FileOutputStream fileOutputStream = new FileOutputStream(outputFilePath) ) { byte[] buf = newbyte[2048]; int len = 0; while ((len = fileInputStream.read(buf)) != -1) { fileOutputStream.write(buf, 0, len); } } catch (IOException e) { e.printStackTrace(); }
Using buffered Input/output Stream
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
String inputFilePath = "C:\\Users\\Taogen\\Desktop\\input.txt"; String outputFilePath = "C:\\Users\\Taogen\\Desktop\\output.txt"; try ( FileInputStream fileInputStream = new FileInputStream(inputFilePath); BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream); FileOutputStream fileOutputStream = new FileOutputStream(outputFilePath); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream); ) {
int b; while ((b=bufferedInputStream.read()) != -1) { bufferedOutputStream.write(b); } } catch (IOException e) { e.printStackTrace(); }
BufferedInputStream‘s default buffer size is int DEFAULT_BUFFER_SIZE = 8192;
BufferedInputStream + Buffer array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
String inputFilePath = "C:\\Users\\Taogen\\Desktop\\recovery_data.sql"; String outputFilePath = "C:\\Users\\Taogen\\Desktop\\recovery_data2.sql"; try ( FileInputStream fileInputStream = new FileInputStream(inputFilePath); BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream); FileOutputStream fileOutputStream = new FileOutputStream(outputFilePath); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream); ) { byte[] buf = newbyte[1024]; int len = 0; while ((len = bufferedInputStream.read(buf)) != -1) { bufferedOutputStream.write(buf, 0, len); } } catch (IOException e) { e.printStackTrace(); }
Time cost: BufferedInputStream + Direct Buffer array < Direct Buffer array < Using a BufferedInputStream < Read Method.
Using BufferedInputStream rather than direct buffer is probably “right” for most applications. Because your used buffer size of direct buffer may be worse than BufferedInputStream default buffer size in speed.
Will making the buffer bigger make I/O go faster? Java buffers typically are by default 1024 or 2048 bytes long. A buffer larger than this may help speed I/O, but often by only a few percent, say 5 to 10%.
Problems
Max upload file size
Character encoding of file name
URL encode of file name
Appendixes
Temporary Files and Directories
java.io.tmpdir
1
System.getProperty("java.io.tmpdir")
Windows 10: C:\Users\{user}\AppData\Local\Temp\
Debian: /tmp
Create temporary file
1 2 3 4
// If you don't specify the file suffix, the default file suffix is ".tmp". File file = File.createTempFile("temp", null); System.out.println(file.getAbsolutePath()); file.deleteOnExit();
Two primary MIME types are important for the role of default types:
text/plain is the default value for textual files. A textual file should be human-readable and must not contain binary data.
application/octet-stream is the default value for all other cases. An unknown file type should use this type. Browsers pay a particular care when manipulating these files, attempting to safeguard the user to prevent dangerous behaviors.