I have a class in Java which write a file using FileOutputStream and BufferedOutputStream. This is working fine but my intention is that I want to write any number of files in java not just one. Here is my code written in Java
public class FileToBeTaken{
public void fileBack(byte [] output) {
FileOutputStream fop = null;
BufferedOutputStream bos = null;
File file;
try {
file= new File("/Users/user/Desktop/newfile.txt");
fop = new FileOutputStream(file);
bos = new BufferedOutputStream(fop);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
bos.write(output);
bos.flush();
bos.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bos != null) {
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Here fileBack method is called from another class inside a for loop n times. so for each time I need to write a new file onto my desktop as my code is I just take only the file for the last iteration. Also I should mention that for each iteration as parameter to this class is send one array of bytes which is taken by "byte [] output
Change
public void fileBack(byte [] output) {
to
public void fileBack(String fileName, byte [] output) {
Then change where you call method fileBack in your other class by providing the file name there. ie
byte output[] = //You already provide this byte array
String fileName = "/Users/user/Desktop/newfile.txt"
fileBack(fileName, output);
Try taking in the file path ..newfile.txt and making it into a parameter for the function. Then you can put a for loop in main or whoever is instantiating this object and call it n times. Does that help at all?
just add one static and private integer field inside FileToBeTaken class.
private static int index=0;
so there is no need to pass name of file to this class as you mentioned in question comments.
because i want to create these file names inside this class i wrote above
then use it in fileBack method and each time incremet it once in that method.
here is the changes on your code:
public class FileToBeTaken {
// index or number of new file, also number of all written files
// because it increments each time you call fileBack method.
private static int index = 0;
public void fileBack(byte[] output) {
FileOutputStream fop = null;
BufferedOutputStream bos = null;
File file;
try {
// use user_dir to place files on desktop,
// even on other machines which have other names except user.
String user_dir = System.getProperty("user.home").replace("\\", "/");
// use index to create name of file.
file = new File(user_dir+"/Desktop/newfile_" + (index++) + ".txt");
fop = new FileOutputStream(file);
bos = new BufferedOutputStream(fop);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
bos.write(output);
bos.flush();
bos.close();
System.out.println("Done - "+file.getName());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bos != null) {
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
how to use it:
for (int i = 0; i < 10; i++) {
new FileToBeTaken().fileBack("some text".getBytes());
}
the output:
Done - newfile_0.txt
Done - newfile_1.txt
Done - newfile_2.txt
Done - newfile_3.txt
Done - newfile_4.txt
Done - newfile_5.txt
Done - newfile_6.txt
Done - newfile_7.txt
Done - newfile_8.txt
Done - newfile_9.txt
Related
This is my method, he create new object "predmet". class "AddNewObject" return me predmet type (name, description).
AddNewPredmet addnewpredmet = new AddNewPredmet();
listPredmet.add(AddNewPredmet.AddPredmet());
StorageInFile.savePredmet(listPredmet);
All working. But I have a problem with the result written in the file. The output file has symbols that are not readable as shown -
¬н sr java.util.ArrayListxЃТ™Зaќ I sizexp w sr entity.PredmetїБц)Зя| L Descriptiont Ljava/lang/String;L PNameq ~ xpt testt testx
The following is the function that writes to the file
public class StorageInFile {
static void savePredmet(List<Predmet> listPredmet) {
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream("Predmet.txt");
oos = new ObjectOutputStream(fos);
oos.writeObject(listPredmet);
oos.flush();
oos.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(StorageInFile.class.getName())
.log(Level.SEVERE, "Нет такого файла", ex);
} catch (IOException ex) {
Logger.getLogger(StorageInFile.class.getName())
.log(Level.SEVERE, "Не могу записать", ex);
}
}}
How i can fix this? I think about method toString(), but i cant add this method to this code.
Try using a buffered writer and use UTF-8 capable viewer to see the file. You are trying to using a tool that assumes a one-byte encoding, such as the Windows-125x encodings. Notepad is an example of such a tool. So using the capable viewer you can look at it.
Also it would help to show what’s in your file
If you expected to print the contents of every instance of Predmet in the List<> then you could try the following.
Implement to the toString() method in Class Predmet
Try the following snippet to write to file.
FileWriter writer = new FileWriter("sample.txt");
try {
int size = listPredMet.size();
for (int index =0; index < size; index++){
writer.write(listPredMet.get(index).toString());
writer.flush();
}
}catch(Exception e){
e.printStackTrace();
}finally{
writer.close()
}
So, I am to write a copy of the sound that I manipulated into a playable format, but whenever I try it, the files are very small (< 1kb), and they don't play, most likely because it is not readable data. Here is the code
public void play(int pause, String filename, String path) throws InterruptedException {
for (int i =0; i < numWords; i++) {
myWordArray[i].blockingPlay();
Thread.sleep(pause); // 300 m.seconds, as listed in main method parameter
File file = new File(path, filename);
try{
PrintWriter output = new PrintWriter(file);
output.println(myWordArray[i]);
output.close();
} catch(IOException ex) {
System.out.printf("ERROR: %s\n", ex);
}
}
}
I'm guessing PrintWriter only works for strings, which is why my WAV file is getting corrupted when I try to play? What should I substitute for this?
EDIT-
So, using the guides posted in the comments, I modified the code, however, now it does not create a file at all. Here is the code in my audio class...
public void play(int pause, String filename, String path) throws InterruptedException {
for (int i =0; i < numWords; i++) {
myWordArray[i].blockingPlay();
Thread.sleep(pause); // 300 m.seconds, as listed in main method parameter
File file = new File("C:\\Users\\Justin\\Desktop\\JavaMedia\\", "thisisatest.wav");
try{
InputStream fis = new FileInputStream(file);
byte[] buffer = new byte[(int)file.length()];
fis.read(buffer, 0, buffer.length);
fis.close();
}
catch(IOException ex){
System.out.printf("ERROR: %s\n", ex);
}
}
}
Here is the call in my main...
myPoem.play(300,"thisisatest_pause.wav", "C:\\Users\\Justin\\Desktop\\JavaMedia\\");
I want the "thisisatest_pause.wav" to be the new file it creates, but it doesn't create one at all.
Because myWordArray[i] is an Object. So it will write myWordArray[i].toString() to the file, not the sound.
Are you using Sound#blockingPlay() from http://coweb.cc.gatech.edu/mediaComp-plan/uploads/101/bookClasses-3-9-10.zip. If yes, it has writeToFile() method to write a sound to file.
I've been trying to tackle this problem for a day or two and can't seem to figure out precisely how to add text files to a zip file, I was able to figure out how to add these text files to a 7zip file which was insanely easy, but a zip file seems to me much more complicated for some reason. I want to return a zip file for user reasons btw.
Here's what I have now:
(I know the code isn't too clean at the moment, I plan to tackle that after getting the bare functionality down).
private ZipOutputStream addThreadDumpsToZipFile(File file, List<Datapoint<ThreadDump>> allThreadDumps, List<Datapoint<String>> allThreadDumpTextFiles) {
ZipOutputStream threadDumpsZipFile = null;
try {
//creat new zip file which accepts input stream
//TODO missing step: create text files containing each thread dump then add to zip
threadDumpsZipFile = new ZipFile(new FileOutputStream(file));
FileInputStream fileInputStream = null;
try {
//add data to each thread dump entry
for(int i=0; i<allThreadDumpTextFiles.size();i++) {
//create file for each thread dump
File threadDumpFile = new File("thread_dump_"+i+".txt");
FileUtils.writeStringToFile(threadDumpFile,allThreadDumpTextFiles.get(i).toString());
//add entry/file to zip file (creates block to add input to)
ZipEntry threadDumpEntry = new ZipEntry("thread_dump_"+i); //might need to add extension here?
threadDumpsZipFile.putNextEntry(threadDumpEntry);
//add the content to this entry
fileInputStream = new FileInputStream(threadDumpFile);
byte[] byteBuffer = new byte[(int) threadDumpFile.length()]; //see if this sufficiently returns length of data
int bytesRead = -1;
while ((bytesRead = fileInputStream.read(byteBuffer)) != -1) {
threadDumpsZipFile.write(byteBuffer, 0, bytesRead);
}
}
threadDumpsZipFile.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileInputStream.close();
} catch(Exception e) {
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return threadDumpsZipFile;
}
As you can sort of guess, I have a set of Thread Dumps that I want to add to my zip file and return to the user.
Let me know if you guys need any more info!
PS: There might be some bugs in this question, I just realized with some breakpoints that the threadDumpFile.length() won't really work.
Look forward to your replies!
Thanks,
Arsa
Here's a crack at it. I think you'll want to keep the file extensions when you make your ZipEntry objects. See if you can implement the below createTextFiles() function; the rest of this works -- I stubbed that method to return a single "test.txt" file with some dummy data to verify.
void zip()
{
try {
FileOutputStream fos = new FileOutputStream("yourZipFile.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
File[] textFiles = createTextFiles(); // should be an easy step
for (int i = 0; i < files.length; i++) {
addToZipFile(file[i].getName(), zos);
}
zos.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
void addToZipFile(String fileName, ZipOutputStream zos) throws Exception {
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(fileName);
zos.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
}
zos.closeEntry();
fis.close();
}
I'm not particularly proficient with Java.
I'm converting an array of bytes to a String (each byte with a decimal representation) and then writing to a file. Here is a minimal example that reproduces the problem that I'm having (I've left the file naming stuff in, just in case it's related):
public class PacketWriter {
public static void writeBytes(byte[] in) {
Calendar cal = Calendar.getInstance();
cal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("ddmmyyHHmmss");
PrintStream out = null;
File outFile = null;
try {
outFile = new File("recpacket"+sdf.format(cal.getTime())+".txt");
outFile.createNewFile(); // also checks for existence of file alre ady
out = new PrintStream(new FileOutputStream(outFile,false));
System.out.println(Arrays.toString(in));
out.print(Arrays.toString(in));
out.flush();
System.out.println("Did the writing!");
} catch (FileNotFoundException e) {
System.err.println("Packet output file not found.");
} catch (IOException e) {
System.err.println("Could not write packets (I/O error).");
}
finally {
System.out.println("Closing...");
if (out != null) out.close();
System.out.println("Closed.");
}
}
}
When I call PacketWriter.writeBytes(/* some nonempty byte array */)
I get the following output:
... array ...
Did the writing!
Closing...
JVM_Close returned -1
Closed.
written to stdout.
The file is empty upon return and does not contain the string that I want it to.
What's going wrong?
The PrintStream class has very poor error reporting: it looks like writing to the file is failing, but it's impossible to know why; it could be because there's no space left in the file system for example. Try using a FileWriter instead:
Writer out = null;
out = new FileWriter(outFile,false);
System.out.println(Arrays.toString(in));
out.write(Arrays.toString(in));
out.flush();
Function " writeToFile() " will be rapidly called to write string to text file .
but I didn't see any text in the file .
code:
public class MyClass {
private File data_file = new File("data_from_java.txt");
public void writeToFile(String str){
try {
FileOutputStream fos= new FileOutputStream(this.data_file, true);
System.out.print(str); // there is text shown in terminal
fos.write(str.getBytes());
fos.flush();
fos.close(); // why file donesn't have text
}catch(Exception ex) {
System.out.println(ex.getMessage());
}
}
Writing raw bytes may cause problems with character encoding. As Jon Skeet said, use a writer...
try {
FileWriter writer = new FileWriter(data_file, true);
writer.write(str);
} catch(IOException e) {
// oh no!
} finally {
writer.close();
}
Try using this chunk of code:
final BufferedWriter fos = new BufferedWriter(new FileWriter(data_file, true));
System.out.print(str);
fos.write(str);
fos.flush();
fos.close();
It worked for me although i did find my text file in a different place than i expected. Maybe a little searching would do already?
IN ur code fos.write(str.getBytes()); this line causes the problem it seems... write() method takes a byte as an argument.. u r giving array of bytes.. So change that line into
buf = str.getBytes();
for (int i=0; i < buf.length; i += 2) {
f0.write(buf[i]);
}