Если мы рассмотрим общие сценарии, в которых может быть выбрано это исключение, доступ к свойствам с объектом вверху.
Пример:
string postalcode=Customer.Address.PostalCode;
//if customer or address is null , this will through exeption
здесь, если адрес имеет значение null, то вы получите NullReferenceException.
Итак, в качестве практики мы всегда должны использовать проверку нуля, прежде чем обращаться к свойствам в таких объектах (особенно в общих)
string postalcode=Customer?.Address?.PostalCode;
//if customer or address is null , this will return null, without through a exception
Использовать Apache Commons IO
FileUtils.writeByteArrayToFile(new File("pathname"), myByteArray)
Или, если вы настаиваете на выполнении работы для себя ...
try (FileOutputStream fos = new FileOutputStream("pathname")) {
fos.write(myByteArray);
//fos.close(); There is no more need for this line since you had created the instance of "fos" inside the try. And this will automatically close the OutputStream
}
File f = new File(fileName);
byte[] fileContent = msg.getByteSequenceContent();
Path path = Paths.get(f.getAbsolutePath());
try {
Files.write(path, fileContent);
} catch (IOException ex) {
Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
}
Это программа, в которой мы читаем и печатаем массив смещений и длины байтов с помощью String Builder и записываем массив длины смещения байтов в новый файл.
`Введите код здесь
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
//*This is a program where we are reading and printing array of bytes offset and length using StringBuilder and Writing the array of bytes offset length to the new file*//
public class ReadandWriteAByte {
public void readandWriteBytesToFile(){
File file = new File("count.char"); //(abcdefghijk)
File bfile = new File("bytefile.txt");//(New File)
byte[] b;
FileInputStream fis = null;
FileOutputStream fos = null;
try{
fis = new FileInputStream (file);
fos = new FileOutputStream (bfile);
b = new byte [1024];
int i;
StringBuilder sb = new StringBuilder();
while ((i = fis.read(b))!=-1){
sb.append(new String(b,5,5));
fos.write(b, 2, 5);
}
System.out.println(sb.toString());
}catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(fis != null);
fis.close(); //This helps to close the stream
}catch (IOException e){
e.printStackTrace();
}
}
}
public static void main (String args[]){
ReadandWriteAByte rb = new ReadandWriteAByte();
rb.readandWriteBytesToFile();
}
}
O / P в консоли: fghij
O / P в новом файле: cdefg
Основной пример:
String fileName = "file.test";
BufferedOutputStream bs = null;
try {
FileOutputStream fs = new FileOutputStream(new File(fileName));
bs = new BufferedOutputStream(fs);
bs.write(byte_array);
bs.close();
bs = null;
} catch (Exception e) {
e.printStackTrace()
}
if (bs != null) try { bs.close(); } catch (Exception e) {}
Так же, как Java 7, одна строка с java.nio.file.Files:
Files.write(new File(filePath).toPath(), data);
Где данные - ваш байт [], а filePath - это String. Вы также можете добавить несколько вариантов открытия файла с классом StandardOpenOptions. Добавьте броски или закруглите с помощью try / catch.
Попробуйте OutputStream
или, более конкретно, FileOutputStream
Традиционным способом преобразования является использование FileOutputStream следующим образом:
public static File convertUsingOutputStream(byte[] fileBytes)
{
File f = new File("C:\\Users\\user\\Desktop\\output\\myfile.pdf");
try (FileOutputStream fos = new FileOutputStream(f)) {
fos.write(fileBytes);
}
catch(Exception ex)
{
ex.printStackTrace();
}
return f;
}
С помощью Java 7 вы можете выполнить преобразование, используя служебный класс Files пакета nio:
public static File convertUsingJavaNIO(byte[] fileBytes)
{
File f = new File("C:\\Users\\user\\Desktop\\output\\myfile.pdf");
try
{
Files.write(f.toPath(), fileBytes);
}
catch (Exception ex)
{
ex.printStackTrace();
}
return f;
}
Помимо JDK, вы можете выполнить преобразование с использованием Apache Common IO-библиотеки следующим образом:
public static File convertUsingCommonsIO(byte[] fileBytes)
{
File f = new File("C:\\Users\\user\\Desktop\\output\\myfile.pdf");
try
{
FileUtils.writeByteArrayToFile(f, fileBytes);
}
catch(Exception ex)
{
ex.printStackTrace();
}
return f;
}
Без каких-либо библиотек:
FileOutputStream stream = new FileOutputStream(path);
try {
stream.write(bytes);
} finally {
stream.close();
}
С помощью Google Guava :
Files.write(bytes, new File(path));
С Apache Commons :
FileUtils.writeByteArrayToFile(new File(path), bytes);
. Все эти стратегии требуют, чтобы вы в какой-то момент тоже заметили исключение IOException.
////////////////////////// 1] Файл для байта [] ////////////// /////
Path path = Paths.get(p);
byte[] data = null;
try {
data = Files.readAllBytes(path);
} catch (IOException ex) {
Logger.getLogger(Agent1.class.getName()).log(Level.SEVERE, null, ex);
}
/////////////////////// 2] Байт [] в файл ///// //////////////////////
File f = new File(fileName);
byte[] fileContent = msg.getByteSequenceContent();
Path path = Paths.get(f.getAbsolutePath());
try {
Files.write(path, fileContent);
} catch (IOException ex) {
Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
}
Я знаю, что это сделано с InputStream
blockquote>На самом деле, вы записываете в файл файла .. .
Другое решение, использующее java.nio.file
:
byte[] bytes = ...;
Path path = Paths.get("C:\myfile.pdf");
Files.write(path, bytes);
Начиная с Java 7, вы можете использовать инструкцию try-with-resources , чтобы избежать утечки ресурсов и упростить чтение кода. Подробнее о том, что здесь .
Чтобы записать ваш byteArray
в файл, который вы сделали бы:
try (FileOutputStream fos = new FileOutputStream("fullPathToFile")) {
fos.write(byteArray);
} catch (IOException ioe) {
ioe.printStackTrace();
}
Вы можете попробовать Cactoos :
new LengthOf(new TeeInput(array, new File("a.txt"))).value();
Подробнее: http://www.yegor256.com/2017/06/22/object-oriented -input-выход-в-cactoos.html