I'm having problems with writing a 2d, user-inputted array to a text file. My code thus far (in the Saving method, at least) is:
`public static void Save(String[][] EntryList)
{
try {
String[][] content = EntryList;
File file = new File("CBB.dat");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
InputStream instream;
OutputStream outstream;
instream = new DataInputStream( new BufferedInputStream(new FileInputStream(file))); // buffers the data stream
outstream = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(file)));
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter writer = new BufferedWriter(fw);
for (int row = 0; row < EntryList.length; ++row)
{
outstream.writeUTF(EntryList[row][1]);
outstream.writeUTF(EntryList[row][2]);
outstream.writeUTF(EntryList[row][3]);
outstream.writeUTF(EntryList[row][4]);
outstream.writeUTF(EntryList[row][5]);
}
outstream.close();
}catch (IOException e) {
e.printStackTrace();
}
}`
However, when I try to compile, I get the error that Java "cannot find symbol - method WriteUTF(String)"
Apparently there is no writeUTF defined for java.io.OutputStream.
You should probably declare outstream as DataOutputStream reference:
DataOutputStream outstream;
as the method writeUTF is defined for DataOutputStream.
Related
With Java:
I have a byte[] that represents a file.
How do I write this to a file (ie. C:\myfile.pdf)
I know it's done with InputStream, but I can't seem to work it out.
Use Apache Commons IO
FileUtils.writeByteArrayToFile(new File("pathname"), myByteArray)
Or, if you insist on making work for yourself...
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
}
Without any libraries:
try (FileOutputStream stream = new FileOutputStream(path)) {
stream.write(bytes);
}
With Google Guava:
Files.write(bytes, new File(path));
With Apache Commons:
FileUtils.writeByteArrayToFile(new File(path), bytes);
All of these strategies require that you catch an IOException at some point too.
Another solution using java.nio.file:
byte[] bytes = ...;
Path path = Paths.get("C:\\myfile.pdf");
Files.write(path, bytes);
Also since Java 7, one line with java.nio.file.Files:
Files.write(new File(filePath).toPath(), data);
Where data is your byte[] and filePath is a String. You can also add multiple file open options with the StandardOpenOptions class. Add throws or surround with try/catch.
From Java 7 onward you can use the try-with-resources statement to avoid leaking resources and make your code easier to read. More on that here.
To write your byteArray to a file you would do:
try (FileOutputStream fos = new FileOutputStream("fullPathToFile")) {
fos.write(byteArray);
} catch (IOException ioe) {
ioe.printStackTrace();
}
Try an OutputStream or more specifically FileOutputStream
Basic example:
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) {}
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);
}
////////////////////////// 1] File to Byte [] ///////////////////
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] Byte [] to File ///////////////////////////
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);
}
I know it's done with InputStream
Actually, you'd be writing to a file output...
This is a program where we are reading and printing array of bytes offset and length using String Builder and Writing the array of bytes offset length to the new file.
`Enter code here
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 in console : fghij
O/P in new file :cdefg
You can try Cactoos:
new LengthOf(new TeeInput(array, new File("a.txt"))).value();
More details: http://www.yegor256.com/2017/06/22/object-oriented-input-output-in-cactoos.html
is it possible to write/create an exe file in Java?
I can successfully read it but writing the exact same data that has been read to a new file seems to create some trouble because Windows tell's me it's not supported for my pc anymore.
This is the code I'm using to read the file where path is a String given with the actual path (it's in the .jar itself that's why I'm using ResourceAsStream()):
try {
InputStream inputStream = FileIO.class.getResourceAsStream(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
ArrayList<String> _final = new ArrayList<String>();
String line;
while ((line = reader.readLine()) != null) {
_final.add(line);
}
inputStream.close();
return _final.toArray(new String[_final.size()]);
}catch(Exception e) {
return null;
}
This is the code I'm using to write the file:
public static void writeFileArray(String path, String[] data) {
String filename = path;
try{
FileWriter fileWriter = new FileWriter(filename);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
for(String d : data) {
bufferedWriter.write(d + "\n");
}
bufferedWriter.close();
}
catch(IOException ex){
System.out.println("FileIO failed to write file, IO exception");
}
}
So it doesn't give me any error's or something and the file size of the original .exe and the 'transferred' .exe stays the same, but it doesn't work anymore. Am I just doing it wrong? Did I forget something? Can u even do this with Java?
Btw I'm not that experienced with reading/writing files..
Thanks for considering my request.
I'm going to guess that you're using a Reader when you should be using a raw input stream. Use BufferedInputStream instead of BufferedReader.
BufferedInputStream in = new BufferedInputStream( inputStream );
The problem is that Reader interprets the binary as your local character set instead of the data you want.
Edit: if you need a bigger hint start with this. I just noticed you're using a BufferedWriter too, that won't work either.
try {
InputStream inputStream = FileIO.class.getResourceAsStream(path);
BufferedInputStream in = new BufferedInputStream( inputStream );
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] bytes = new byte[ 1024 ];
for( int length; ( length = ins.read( bytes ) ) != -1; )
bos.write( bytes, 0, length );
}
inputStream.close();
return bos;
When you are using Java 7 or newer, you should copy a resource to a file using
public static void copyResourceToFile(String resourcePath, String filePath) {
try(InputStream inputStream = FileIO.class.getResourceAsStream(resourcePath)) {
Files.copy(inputStream, Paths.get(filePath));
}
catch(IOException ex){
System.out.println("Copying failed. "+ex.getMessage());
}
}
This construct ensures correct closing of the resources even in the exceptional case and the JRE method ensures correct and efficient copying of the data.
It accepts additional options, e.g. to specify that the target file should be overwritten in case it already exists, you would use
public static void copyResourceToFile(String resourcePath, String filePath) {
try(InputStream inputStream = FileIO.class.getResourceAsStream(resourcePath)) {
Files.copy(inputStream, Paths.get(filePath), StandardCopyOption.REPLACE_EXISTING);
}
catch(IOException ex){
System.out.println("Copying failed. "+ex.getMessage());
}
}
You are using InputStreams for strings, .exe files are bytes!
Try using a ByteArrayInputStream and ByteArrayOutputStream.
Edit: completing with markspace's answer:
new BufferedInputStream(new ByteArrayInputStream( ... ) )
I followed this link and I came up with below code
try {
File file = new File(
"C:/dataset.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
List<Integer> data = generateData(args);
// one per line
for (final int i : data) {
bw.write(i);
bw.newLine(); // Here it throws NullPointerException
}
bw.close();
} catch (IOException e) {
System.out.print(e);
}
NOTE: Even if I move bw.newLine(); before for loop, it throws NullPointerException.
Image
Am I missing anything ?
To add a line seperator you could use this.
//to add a new line after each value added to File
String newLine = System.getProperty("line.separator");
and then call it like so:
bw.write(newLine);
EDIT:
since you cant use a System.getProperty with a BufferWriter I would suggest the code below:
private FileOutputStream fOut;
private OutputStreamWriter writer;
fOut = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
writer = new OutputStreamWriter(fOut);
writer.append(.... whatever you wish to append ...);
writer.append(separator);
writer.flush();
fOut.close();
Hope that helps!
Here I am using poi-jar to export data from database to excel it working fine . But here I want change instead of creating manual path. I wanted make that as to download automatically with out creating any manual path like this:
OutputStream file = new FileOutputStream(new File("D:\\venki1213.xls"));
And this is my code:
Session ses = HibernateUtil.getSessionFactory().openSession();
String query;
query = "from LibraryImportEntity ";
List<LibraryImportEntity> list = ses.createQuery(query).list();
ses.close();
System.out.println("list size" + list.size());
String filename = "D://ranjith//ranjith1213.xls";
OutputStream file = new FileOutputStream(new File("D:\\venki1213.xls"));
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("new sheet");
HSSFRow rowhead = sheet.createRow((short) 0);
rowhead.createCell(0).setCellValue("Sl.No");
rowhead.createCell(1).setCellValue("Magazine Name");
rowhead.createCell(2).setCellValue("Volume No");
rowhead.createCell(3).setCellValue("Issue No");
rowhead.createCell(4).setCellValue("Cost");
int i = 1;
for (LibraryImportEntity l1 : list) {
System.out.println("sl_no" + l1.getSl_no());
System.out.println("Magazinename" + l1.getMagazinename());
System.out.println("sl_no" + l1.getVolumeno());
System.out.println("sl_no" + l1.getCost());
HSSFRow row = sheet.createRow((short) i);
row.createCell(0).setCellValue(l1.getSl_no());
row.createCell(1).setCellValue(l1.getMagazinename());
row.createCell(2).setCellValue(l1.getVolumeno());
row.createCell(3).setCellValue(l1.getIssueno());
row.createCell(4).setCellValue(l1.getCost());
i++;
}
try {
FileOutputStream fileOut = new FileOutputStream(filename);
hwb.write(file);
fileOut.close();
} catch (IOException ex) {
Logger.getLogger(LibraryExportDAO.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Your excel file has been generated!");
return "success";
}
If you are generating the excel in a browser just call the method you want to generate the excel file based on a url and set the response properties like this,
//1.Fill the data from db
//2.Set the response properties
String fileName = "Excel.xls";
response.setHeader("Content-Disposition", "inline; filename=" + fileName);
// Make sure to set the correct content type(the below content type is ok)
response.setContentType("application/vnd.ms-excel");
//3.Write to the output stream
Writer.write();//call write method of Writer class to write the data to o/p stream
Writer Class:
public class Writer {
private static Logger logger = Logger.getLogger("service");
/**
* Writes the report to the output stream
*/
public static void write(HttpServletResponse response, HSSFSheet worksheet) {
logger.debug("Writing excel data to the stream");
try {
// Retrieve the output stream
ServletOutputStream outputStream = response.getOutputStream();
// Write to the output stream
worksheet.getWorkbook().write(outputStream);
// Flush the stream
outputStream.flush();
}
catch (Exception e) {
logger.error("Unable to write excel data to the output stream");
}
}
}
In the response receiving end you'll be prompted to download the file in the browser window..
LINK
Instead of this code,
OutputStream file = new FileOutputStream(new File("D:\\venki1213.xls"));
Use,
OutputStream file = new FileOutputStream(new File("venki1213.xls"));
This will create a file in project folder.
Cheers ...... !
You have to write the file to response
ByteArrayOutputStream bos = null;
try {
File file = new File(filename);
FileInputStream fis = new FileInputStream(file);
bos = new ByteArrayOutputStream();
if (fis != null) {
byte[] buf = new byte[(int) file.length()];
for (int num; (num = fis.read(buf)) != -1;) {
bos.write(buf, 0, num);
}
}
byte[] bytes = bos.toByteArray();
response.setContentType("application/vnd.ms-excel");
final OutputStream fileOutputStream = response.getOutputStream();
fileOutputStream.write(bytes);
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e) {
}
How can i append two audio files in android. I tried this but it does not work. pls give me a soln.I need to concatenate the files from sdcard that ts A.mp3 and B.mp3 .When i merge concatenate method calls i want both of them as a single file in sdcard that is C.mp3........
File original= new File("/mnt/sdcard/A.mp3");
File temp=new File("/mnt/sdcard/B.mp3");
Log.i("...............",""+path);
try {
File outFile= new File("/mnt/sdcard/C.mp3 ");
DataOutputStream out=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));
// FileOutputStream out=new FileOutputStream(outFile);
//OutputStream out = new FileOutputStream(original,true);
int m,n;
m=(int) temp.length();
n=(int) original.length();
byte[] buf1 = new byte[m];
byte[] buf2 = new byte[n];
byte[] outBytes = new byte[m+n];
DataInputStream dis1=new DataInputStream( new BufferedInputStream(new FileInputStream(original)));
DataInputStream dis2=new DataInputStream( new BufferedInputStream(new FileInputStream(temp)));
dis1.read(buf1, 0, m);
dis1.close();
dis2.readFully(buf2, 0, n);
dis2.close();
out.write(buf1);
out.write(buf2);
out.flush();
//in.close();
out.close();
System.out.println("File copied.");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I need to combine The File A.mp3,B.mp3 to C.mp3....
In addition to the answer of knowbody, you can refer to the mp3 file format specification for more information HERE and HERE.
There are a lot of things you should consider when stitching two mp3 files. The least to say is that they need to be encoded by the same program, with the same settings or if we're speaking about voice, to be taken from the same microphone, set with the same settings etc.
import java.io.*;
public class TwoFiles
{
public static void Main(String args[]) throws IOException
{
FileInputStream fistream1 = new FileInputStream("C:\\Temp\\1.mp3");
FileInputStream fistream2 = new FileInputStream("C:\\Temp\\2.mp3");
SequenceInputStream sistream = new SequenceInputStream(fistream1, fistream2);
FileOutputStream fostream = new FileOutputStream("C:\\Temp\\final.mp3");
int temp;
while( ( temp = sistream.read() ) != -1)
{
fostream.write(temp);
}
fostream.close();
sistream.close();
fistream1.close();
fistream2.close();
}
}
I hope is clear