I am working on a simple application which needs the facility to read in all the .wav files in a specified directory (/audiofiles), and then concatenate them. I have working code which gets the names of all the files in the directory and prints them to the console, and code which concatenates a list of specified files, but I cannot seem to combine the two functions. Any suggestions?
So far:-
import java.util.*;
import java.io.*;
import javax.sound.sampled.*;
public class getconc_1 {
public static void main(String[] args) {
// get list of file names from audio directory
File audDir = new File("/audiofiles");
//define a list to contain the audio files names and path
File[] filesList = audDir.listFiles();
// assign contents of each wav file from filesList to a string
String wavFile1 = filesList.get(0);
String wavFile2 = filesList.get(1);
// read the string from the audio file into an AudioInputStream, and concatenate
try {
AudioInputStream clip1 = AudioSystem.getAudioInputStream(new File(wavFile1));
AudioInputStream clip2 = AudioSystem.getAudioInputStream(new File(wavFile2));
AudioInputStream appendedFiles =
new AudioInputStream(
new SequenceInputStream(clip1, clip2),
clip1.getFormat(),
clip1.getFrameLength() + clip2.getFrameLength());
AudioSystem.write(appendedFiles,
AudioFileFormat.Type.WAVE,
new File("wavAppended.wav"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
First of all you have error in your codes
String wavFile1 = filesList.get(0);
String wavFile2 = filesList.get(1);
Should be replaced by
String wavFile1 = filesList[0].getPath();
String wavFile2 = filesList[1].getPath();
Secondly use
new SequenceInputStream(Collections.enumeration(list)) to join multiple streams into one.
I have not added few checks in the program like checking the size and null check for clip object.
import java.util.*;
import java.io.*;
import javax.sound.sampled.*;
public class getconc_1 {
public static void main(String[] args) {
// get list of file names from audio directory
File audDir = new File("/audiofiles");
//define a list to contain the audio files names and path
File[] filesList = audDir.listFiles();
// assign contents of each wav file from filesList to a string
// read the string from the audio file into an AudioInputStream, and concatenate
try {
long length = 0;
AudioInputStream clip = null;
List<AudioInputStream> list = new ArrayList<AudioInputStream>();
for (File file:filesList ) {
clip = AudioSystem.getAudioInputStream(new File(file.getPath()));
list.add(clip);
length += clip.getFrameLength();
}
if(length>0 && list.size()>0 && clip!=null) {
AudioInputStream appendedFiles =
new AudioInputStream(
new SequenceInputStream(Collections.enumeration(list)),
clip.getFormat(),
length);
AudioSystem.write(appendedFiles,
AudioFileFormat.Type.WAVE,
new File("wavAppended12.wav"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Related
In my program I suppose to copy a directory to another directory with java. I did it but the only problem is that for the directories that are inside the source directory get copied but not the file inside them. Why?
This is the assigment:
Ask the user for the source directory and a destination. The source is the directory to be copied; the destination is the directory that will be the parent of the new copy.
First your program should make a new directory in the new location with the same name as the source directory. (You may need to do something special for root directories if you are copying an entire disk. A root directory has no parent directory, and often, no name.)
Then your program should create an array with File class objects for each item in the contents of the source directory, similar to what was done in DirectoryListDemo.
Next , it should iterate the array, and for each item in the array,
if it is a file, copy the file to the new directory using the copyFile() method taken from CopyFileDemoE.
if it is a directory, recursively call this method to copy the directory and all of its contents.
Here is the code:
package com.company;
import java.io.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
Scanner src = new Scanner(System.in);
System.out.println("Enter name of source directory to copy from: ");
String sourceFile= src.nextLine();
System.out.println("Enter name of destination directory to copy the files into: ");
String destinationFile = (src.nextLine()+"/"+sourceFile);
isDirFile(sourceFile, destinationFile);
}
public static void isDirFile(String source, String dest) throws Exception{
File sourceFile = new File ("C:/"+source);
File dirFile = new File (dest, new File(source).getName());
dirFile.mkdirs();
File[] entries;
if (dirFile.exists()){
if (sourceFile.isDirectory()){
entries = sourceFile.listFiles();
assert entries != null;
for (File entry:entries){
if(entry.isFile()){
copyFile(entry.getAbsolutePath(),dest);
}
else{
isDirFile(entry.getAbsolutePath(),dest);
}
}
}
}
else{
System.out.println("File does not exist");
}
}
public static void copyFile(String source, String destination) throws Exception{
File sourceFile;
File destFile;
FileInputStream sourceStream;
FileOutputStream destSteam;
BufferedInputStream bufferedSource = null;
BufferedOutputStream bufferedDestination = null;
try{
sourceFile = new File(source);
destFile = new File (destination, new File(source).getName());
sourceStream = new FileInputStream(sourceFile);
destSteam = new FileOutputStream(destFile);
bufferedSource = new BufferedInputStream(sourceStream, 8182);
bufferedDestination = new BufferedOutputStream(destSteam, 8182);
int transfer;
System.out.println("Beginning file copy: ");
System.out.println("\tcopying "+ source);
System.out.println("\tto "+destination);
while ((transfer = bufferedSource.read()) != -1){
bufferedDestination.write(transfer);
}
}
catch (IOException e){
e.printStackTrace();
System.out.println(" An unexpected I/O error occurred.");
}
finally {
if(bufferedSource != null){
bufferedSource.close();
}
if(bufferedDestination != null){
bufferedDestination.close();
}
System.out.println("Files closed. Copy complete.");
}
}
}
I am using POI to delete "enter" in a .doc file (Blank line).
My code below works correctly when the input file is not large (for example, less than 1MB). However, when I deal with large input.doc that is 4mb, the output.doc is not correctly generated. I can not open the file.
Does anyone have better idea to write the big file correctly? Or, is there any other java code that can delete "enter" in a big .doc file? Thank you very much.
package mydoc;
import org.apache.poi.poifs.filesystem.*;
import org.apache.poi.hwpf.*;
import org.apache.poi.hwpf.usermodel.*;
import java.io.*;
public class test {
/*The ASCII of "Enter" is 13*/
private static final short ENTER_ASCII = 13;
public static void main(String[] args){
/* the location of the input file */
String fileName = "D:\\input.doc";
deleteEnter(fileName);
}
public static void deleteEnter(String fileName){
POIFSFileSystem fs = null;
try{
fs = new POIFSFileSystem(new FileInputStream(fileName));
HWPFDocument doc = new HWPFDocument(fs);
Range range = doc.getRange();
for (int i = 0; i < range.numParagraphs(); i++)
{
if (range.getParagraph(i).text().toCharArray()[0]==ENTER_ASCII)
{
range.getParagraph(i).delete();
}
}
FileOutputStream fos = null;
fos = new FileOutputStream(new File("D:\\output.doc"));
doc.write(fos);
fos.flush();
fos.close();
}//end try
catch (Exception e){
e.printStackTrace();
}//end catch
}
}
Depending on your needs you could even use a macro;
You should even be able to use regex like this: "^13{2,}", but that didn't work for me in Word 2010, see http://social.msdn.microsoft.com/Forums/en-US/0d921f97-b59a-48a9-a01a-20fe72f21c19/how-to-remove-blank-lines-?forum=worddev
Sub RemoveBlankLines()
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "^p^p"
.Replacement.Text = "^p"
.MatchWildcards = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub
Sub RemoveEnters()
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
'^11 or ^l New line
.Text = "^l"
.Replacement.Text = ""
End With
Selection.Find.Execute Replace:=wdReplaceAll
With Selection.Find
'^13 or ^p Carriage return/paragraph mark
.Text = "^p"
.Replacement.Text = ""
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub
"enter" is the line separator right ? It's platform dependant so I propose the above solution :
String separator = System.getProperty("line.separator")
file = new File(filename);
FileInputStream fis=new FileInputStream(file.getAbsolutePath());
HWPFDocument document=new HWPFDocument(fis);
extractor = new WordExtractor(document);
String [] fileData = extractor.getParagraphText();
for(int i=0;i<fileData.length;i++){
if(fileData[i] != null)
fileData[i] = fileData[i].replace(separator,"");
}
And then you just have to output fileData in a clean doc file.
I'm trying to write a file from an AudioInputStream. The stream can read the original file just fine (as far as I can tell). But when it tries to write, it writes what should be a 15 KB file in 44 bytes. Windows Media Player gives the error "either the file type is unsupported, or WMP doesn't recognize the codec used to convert the file."
I got most of this code from http://docs.oracle.com/javase/tutorial/sound/converters.html. I've looked all over StackOverflow but nothing seemed to pertain to this problem.
I've tried getting the format of the AudioInputStream and it's definitely a .wav. As far as I can tell, a codec is software that converts analog to digital data, and both the wav file and the AudioInputStream are digital already.
EDIT: It looks like the stream is writing the WAVE file header to my new file, but nothing else. That's where my 44 byte file is coming from.
Here's the code. I think the problem is in writeFile() but I included the rest just in case:
public static void getFile()
{
try
{
File test = new File("C:\\Users\\Audrey\\Steganography\\correctamundo.wav"); //file to be written from
AudioInputStream stream = AudioSystem.getAudioInputStream(test);
AudioFileFormat format = AudioSystem.getAudioFileFormat(test);
int bytesPerFrame = stream.getFormat().getFrameSize();
byte[] b = new byte[30000]; //array of arbitrary size to hold the bytes in stream
if (bytesPerFrame == AudioSystem.NOT_SPECIFIED) //not sure why this is necessary
{
bytesPerFrame = 1;
}
int i = 0;
while(stream.available() > 0)
{
byte currentByte = (byte)stream.read();
b[i] = currentByte; //read bytes to array
System.out.println(b[i] + " " +(i+1)); //test statement
i++;
}
writeFile(format, stream);
} catch (IOException | UnsupportedAudioFileException e)
{
e.printStackTrace();
}
}
public static void writeFile (AudioFileFormat format, AudioInputStream stream) //format and stream created in getFile() under the same names
{
try
{
File fileOut = new File("C:\\Users\\Audrey\\Steganography\\testFile2.wav");
AudioFileFormat.Type fileType = format.getType(); //type of file the AudioInputStream can write to, since format refers to stream
if (AudioSystem.isFileTypeSupported(fileType, stream))
{
AudioSystem.write(stream, fileType, fileOut);
System.out.println(stream.getFrameLength()); //test statement
}
System.out.println(fileType); //test statement
}
catch (IOException e)
{
e.printStackTrace();
}
}
I am trying to implement program to zip and unzip a file. All I want to do is to zip a file (fileName.fileExtension) with name as fileName.zip and on unzipping change it again to fileName.fileExtension.
This is how I used to rename files or change its extension.
public static void modify(File file)
{
int index = file.getName().lastIndexOf(".");
//print filename
//System.out.println(file.getName().substring(0, index));
//print extension
//System.out.println(file.getName().substring(index));
String ext = file.getName().substring(index);
//use file.renameTo() to rename the file
file.renameTo(new File("Newname"+ext));
}
edit: John's method renames the file (keeping the extension). To change the extension do:
public static File changeExtension(File f, String newExtension) {
int i = f.getName().lastIndexOf('.');
String name = f.getName().substring(0,i);
return new File(f.getParent(), name + newExtension);
}
This changes only the last extension to a filename, i.e. the .gz part of archive.tar.gz. Therefore it works fine with Linux hidden files, for which the name starts with a .
This is quite safe because if getParent() returns null (i.e. in the event of the parent being the system root) it is "cast" to an empty String as the whole argument to the File constructor is evaluated first.
The only case where you will get a funny output is if you pass in a File representing the system root itself, in which case the null is prepended to the rest of the path string.
Try with:
File file = new File("fileName.zip"); // handler to your ZIP file
File file2 = new File("fileName.fileExtension"); // destination dir of your file
boolean success = file.renameTo(file2);
if (success) {
// File has been renamed
}
I would check, if the file has an extension before changing. The solution below works also with files without extension or multiple extensions
public File changeExtension(File file, String extension) {
String filename = file.getName();
if (filename.contains(".")) {
filename = filename.substring(0, filename.lastIndexOf('.'));
}
filename += "." + extension;
file.renameTo(new File(file.getParentFile(), filename));
return file;
}
#Test
public void test() {
assertThat(changeExtension(new File("C:/a/aaa.bbb.ccc"), "txt"),
is(new File("C:/a/aaa.bbb.txt")));
assertThat(changeExtension(new File("C:/a/test"), "txt"),
is(new File("C:/a/test.txt")));
}
By the same logic as mentioned #hsz, but instead simply use replacement:
File file = new File("fileName.fileExtension"); // creating object of File
String str = file.getPath().replace(".fileExtension", ".zip"); // replacing extension to another
file.renameTo(new File(str));
I want to avoid the new extension just happening to be in the path or filename itself. I like a combination of java.nio and apache StringFilenameUtils.
public void changeExtension(Path file, String extension) throws IOException {
String newFilename = FilenameUtils.removeExtension(file.toString()) + EXTENSION_SEPARATOR_STR + extension;
Files.move(file, Paths.get(newFilename, StandardCopyOption.REPLACE_EXISTING));
}
If you are using Kotlin you can use from this property of your file object:
file.nameWithoutExtension + "extension"
FilenameUtils.getFullPathNoEndSeparator(doc.getDocLoc()) + "/" +
FilenameUtils.getBaseName(doc.getDocLoc()) + ".xml"
My firend was working on a zipper in Java some 4 months back, I got this code from him.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipFiles {
List<String> filesListInDir = new ArrayList<String>();
public static void main(String[] args) {
File file = new File("/Users/pankaj/sitemap.xml");
String zipFileName = "/Users/pankaj/sitemap.zip";
File dir = new File("/Users/pankaj/tmp");
String zipDirName = "/Users/pankaj/tmp.zip";
zipSingleFile(file, zipFileName);
ZipFiles zipFiles = new ZipFiles();
zipFiles.zipDirectory(dir, zipDirName);
}
/**
* This method zips the directory
* #param dir
* #param zipDirName
*/
private void zipDirectory(File dir, String zipDirName) {
try {
populateFilesList(dir);
//now zip files one by one
//create ZipOutputStream to write to the zip file
FileOutputStream fos = new FileOutputStream(zipDirName);
ZipOutputStream zos = new ZipOutputStream(fos);
for(String filePath : filesListInDir){
System.out.println("Zipping "+filePath);
//for ZipEntry we need to keep only relative file path, so we used substring on absolute path
ZipEntry ze = new ZipEntry(filePath.substring(dir.getAbsolutePath().length()+1, filePath.length()));
zos.putNextEntry(ze);
//read the file and write to ZipOutputStream
FileInputStream fis = new FileInputStream(filePath);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
zos.closeEntry();
fis.close();
}
zos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* This method populates all the files in a directory to a List
* #param dir
* #throws IOException
*/
private void populateFilesList(File dir) throws IOException {
File[] files = dir.listFiles();
for(File file : files){
if(file.isFile())
filesListInDir.add(file.getAbsolutePath());
else
populateFilesList(file);
}
}
/**
* This method compresses the single file to zip format
* #param file
* #param zipFileName
*/
private static void zipSingleFile(File file, String zipFileName) {
try {
//create ZipOutputStream to write to the zip file
FileOutputStream fos = new FileOutputStream(zipFileName);
ZipOutputStream zos = new ZipOutputStream(fos);
//add a new Zip Entry to the ZipOutputStream
ZipEntry ze = new ZipEntry(file.getName());
zos.putNextEntry(ze);
//read the file and write to ZipOutputStream
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
//Close the zip entry to write to zip file
zos.closeEntry();
//Close resources
zos.close();
fis.close();
fos.close();
System.out.println(file.getCanonicalPath()+" is zipped to "+zipFileName);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I haven't tried it personally, but he and also some of my other friends told me that it works.
here i'm trying to zip only .txt file in a folder using java.
My code here was found with google and works perfectly but only for a specified .txt file.
Thank you.
import java.util.*;
import java.util.zip.*;
import java.io.*;
public class ZipFile
{
public static void main(String[] args) {
ZipOutputStream out = null;
InputStream in = null;
try {
File inputFile1 = new File("c:\\Target\\target.txt");// here i want to say only the directroy where .txt files are stored
File outputFile = new File("c:\\Target\\Archive_target.zip");//here i want to put zipped file in a different directory
OutputStream rawOut = new BufferedOutputStream(new FileOutputStream(outputFile));
out = new ZipOutputStream(rawOut);
InputStream rawIn = new FileInputStream(inputFile1);
in = new BufferedInputStream(rawIn);
ZipEntry entry = new ZipEntry("c:\\Target\\target.txt");
out.putNextEntry(entry);
byte[] buf = new byte[2048];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
catch(IOException e) {
e.printStackTrace();
}
finally {
try {
if(in != null) {
in.close();
}
if(out != null) {
out.close();
}
}
catch(IOException ignored)
{ }
}
}
}
You need to use File.list(...) to get a list of all the text files in the folder. Then you create a loop to write each file to the zip file.
I just add these lines just after
"File outputFile = new File("c:\Target\Archive_target.zip");
from my previous code.
code added:
File Dir = new File("c:/Target");
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return !name.startsWith(".txt");
}
};
String[] children = Dir.list(filter);
You can get a list of all text files in your directory by using the following method of the File class:
String[] list(FilenameFilter filter)
Create a File object that points to your DIRECTORY (I know it sounds illogical, but that's the way it is- you can test if it is a directory using isDirectory()) and then use the FilenameFilter to say, for example, accept this file if its name contain ".txt"
Create a FilenameFilter that accepts only *.txt file , and then just use
list = File.list(yourNameFilter);
and then just add all the files in the list to the zip file