Java - המרת קובץ ל- InputStream

1. סקירה כללית

במדריך מהיר זה אנו הולכים להראות כיצד להמיר א קוֹבֶץ ל InputStream- תחילה באמצעות Java רגיל ואז גויאבה וספריית ה- IO של Apache Commons.

מאמר זה הוא חלק מה- "ג'אווה - חזרה לבסיסיסדרה כאן על באלדונג.

2. להמיר באמצעות ג'אווה

אנו יכולים להשתמש בחבילת ה- IO של java כדי להמיר a קוֹבֶץ לשונה InputStreamס.

2.1. FileInputStream

נתחיל עם הראשון ו הפשוטה ביותר - באמצעות א FileInputStream:

@Test הציבור בטל givenUsingPlainJava_whenConvertingFileToInputStream_thenCorrect () זורק IOException {File initialFile = קובץ חדש ("src / main / resources / sample.txt"); InputStream targetStream = FileInputStream חדש (initialFile); }

2.2. DataInputStream

בואו נראה אחד אחר, איפה שאנחנו יכולים להשתמש DataInputStream לקריאת נתונים בינאריים או פרימיטיביים מקובץ:

@Test הסופי הציבורי בטל givenUsingPlainJava_whenConvertingFileToDataInputStream_thenCorrect () זורק IOException {final File initialFile = קובץ חדש ("src / test / resources / sample.txt"); סופי InputStream targetStream = DataInputStream חדש (FileInputStream חדש (initialFile)); }

2.3. SequenceInputStream

לבסוף, בואו נסתכל גם כיצד להשתמש SequenceInputStream לשרשור זרם קלט של שני קבצים ליחיד InputStream:

@Test ציבורי חלל סופי givenUsingPlainJava_whenConvertingFileToSequenceInputStream_thenCorrect () זורק IOException {final File initialFile = קובץ חדש ("src / test / resources / sample.txt"); הקובץ הסופי anotherFile = קובץ חדש ("src / test / resources / anothersample.txt"); סופי InputStream targetStream = FileInputStream חדש (initialFile); סופי InputStream anotherTargetStream = FileInputStream חדש (anotherFile); InputStream sequenceTargetStream = SequenceInputStream חדש (targetStream, AnotherTargetStream); }

שים לב שאנחנו לא סוגרים את הזרם שנוצר בדוגמאות אלה לצורך קריאות.

3. להמיר באמצעות גויאבה

הבא - בואו נראה פיתרון הגויאבה, באמצעות מתווך ByteSource:

@Test הציבור בטל givenUsingGuava_whenConvertingFileToInputStream_thenCorrect () זורק IOException {File initialFile = קובץ חדש ("src / main / resources / sample.txt"); InputStream targetStream = Files.asByteSource (initialFile) .openStream (); }

4. המירו באמצעות IO של Commons

לסיום - בואו נסתכל על פיתרון באמצעות Apache Commons IO:

@Test הציבור בטל givenUsingCommonsIO_whenConvertingFileToInputStream_thenCorrect () זורק IOException {File initialFile = קובץ חדש ("src / main / resources / sample.txt"); InputStream targetStream = FileUtils.openInputStream (initialFile); }

ויש לך את זה - 3 פתרונות פשוטים ונקיים לפתיחת זרם מקובץ Java.

5. מסקנה

במאמר זה בחנו דרכים שונות כיצד להמיר a קוֹבֶץ ל InputStream באמצעות ספריות שונות.

ניתן למצוא את היישום של כל הדוגמאות וקטעי הקוד ב- GitHub - זהו פרויקט מבוסס Maven, כך שיהיה קל לייבא ולהפעיל אותו כפי שהוא.


$config[zx-auto] not found$config[zx-overlay] not found