I recorded some audio files, stored them in sdcard. I need to combine all the recorded files into a single audiofile. I used the following code. My problem is the combined file contains only the first recorded file. Any suggestions...In readAudioAsStream() method i tried to combine the files.
public void readAudioAsStream() {
getFullAudioPath()
File f;
FileInputStream ins = null;
try
{
String comfile=getCombineFile();
//FileOutputStream fos=new FileOutputStream(comfile);
Log.d("combined file",comfile);
File file=new File(comfile);
RandomAccessFile raf = new RandomAccessFile(file, "rw");
Log.d("path size",Integer.toString(audFullPath.size()));
for (int i=0;i<audFullPath.size();i++)
{
String filepath=audFullPath.get(i);
Log.d("Filepath",filepath);
f=new File(audFullPath.get(i));
fileContent = new byte[(int)f.length()];
ins=new FileInputStream(audFullPath.get(i));
int numofbytes=ins.read(fileContent);
System.out.println("Number Of Bytes Read===========>>>"+numofbytes);
raf.seek(file.length());
raf.write(fileContent);
}
}
catch (FileNotFoundException e1) {
e1.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
public ArrayList<String> getFullAudioPath() {
ArrayList<String> fullPath=new ArrayList<String>();
fullPath.clear();
String path=filePath();
File f=new File(path);
if(f.isDirectory())
{
File[] files=f.listFiles();
for(int i=0;i<files.length;i++)
{
String fpath=path+File.separator+files[i].getName().toString().trim();
System.out.println("File Full Path======>>>"+fpath);
fullPath.add(fpath);
}
}
return fullPath;
}
public String filePath() {
String newFolderName="/MyAudio";
String extstoredir=Environment.getExternalStorageDirectory().toString();
String newPath=extstoredir+newFolderName;
return newPath;
}
public String getCombineFile() {
String newFolderName="/MyComAudio";
String extstoredir=Environment.getExternalStorageDirectory().toString();
String path=extstoredir+newFolderName;
File myNewPath=new File(path);
if(!myNewPath.exists()) {
myNewPath.mkdir();
}
String audname="ComAudio";
String ext=".3gp";
File audio=new File(myNewPath,audname+ext);
if(audio.exists()) {
audio.delete();
}
String audpath=path+"/"+audname+ext;
Log.d("Combined audio file",audpath);
return audpath;
}
You can't merge two .3gp files just by writing content of one .3gp file at the end of another .3gp file.
Related
I have made the code which renames all the jpg files in a directory from 1 to n (number of files)..
if there were let say 50 jpg files that after running the program all the files are renamed to 1.jpg ,2.jpg and so on till 50.jpg
But i am facing the problem if I manually rename the file let say 50.jpg to aaa.jpg then again running the program doesn't rename that file
I have wasted one day to resove that issue
Kindly help me
Code:
public class Renaming {
private static String path; // string for storing the path
public static void main(String[] args) {
FileReader fileReader = null; // filereader for opening the file
BufferedReader bufferedReader = null; // buffered reader for buffering the data of file
try{
fileReader = new FileReader("input.txt"); // making the filereader object and paasing the file name
bufferedReader = new BufferedReader(fileReader); //making the buffered Reader object
path=bufferedReader.readLine();
fileReader.close();
bufferedReader.close();
}
catch (FileNotFoundException e) { // Exception when file is not found
e.printStackTrace();
}
catch (IOException e) { // IOException
e.printStackTrace();
}
finally {
File directory=new File(path);
File[] files= directory.listFiles(); // Storing the all the files in Array
int file_counter=1;
for(int file_no=0;file_no<files.length;file_no++){
String Extension=getFileExtension(files[file_no]); //getting the filw extension
if (files[file_no].isFile() && (Extension .equals("jpg")|| Extension.equals("JPG"))){ // checking that if file is of jpg type then apply renaming // checking thaat if it is file
File new_file = new File(path+"\\"+files[file_no].getName()); //making the new file
new_file.renameTo(new File(path+"\\"+String.valueOf(file_no+1)+".jpg")); //Renaming the file
System.out.println(new_file.toString());
file_counter++; // incrementing the file counter
}
}
}
}
private static String getFileExtension(File file) { //utility function for getting the file extension
String name = file.getName();
try {
return name.substring(name.lastIndexOf(".") + 1); // gettingf the extension name after .
} catch (Exception e) {
return "";
}
}`
first of all, you should use the path separator / . It's work on Windows, Linux and Mac OS.
This is my version of your problem to rename all files into a folder provide. Hope this will help you. I use last JDK version to speed up and reduce the code.
public class App {
private String path = null;
public static int index = 1;
public App(String path){
if (Files.isDirectory(Paths.get( path ))) {
this.path = path;
}
}
public void rename() throws IOException{
if ( this.path != null){
Files.list(Paths.get( this.path ))
.forEach( f ->
{
String fileName = f.getFileName().toString();
String extension = fileName.replaceAll("^.*\\.([^.]+)$", "$1");
try {
Files.move( f ,Paths.get( this.path + "/" + App.index + "." + extension));
App.index++;
} catch (IOException e) {
e.printStackTrace();
}
}
);
}
}
public static void main(String[] args) throws IOException {
App app = new App("c:/Temp/");
app.rename();
}
}
I am developing an Android application that produces results and I am saving this results in a CSV file. After that I want to close the app, open it again, get other results and write them at the end of the same existing CSV file. Right now every time it ovverrides the previous results.
This is my class to save the results in a CSV file:
public class SaveCSV {
private File file;
private RandomAccessFile randomAccessFile;
public SaveCSV(){
this.file = getPath("RisultatiTest.csv");
try {
this.randomAccessFile = new RandomAccessFile(file, "rwd");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void salvaRisultati (int[] array) {
try {
file.createNewFile();
String s = "";
for (int i = 0; i < array.length; i++) {
s = s + array[i] + ",";
}
randomAccessFile.writeBytes(s);
randomAccessFile.writeBytes("\n");
} catch (IOException e) {
throw new RuntimeException("Unable to create File " + e);
}
}
public static File getPath(String fileName){
return new File(Environment.getExternalStorageDirectory(), fileName);
}
}
I am new for android, Im downloading image from URL and set in listView. Its working some mobile and not creating file/directory in some mobile.
Its throw error like:
java.io.FileNotFoundException: /storage/emulated/0/.tam/veg.png: open failed: ENOENT (No such file or directory)
I don't know why its throw error like this some mobile. I want to create directory all type of mobile. Please anyone help me.
Here my code:
public class ImageStorage {
public static String saveToSdCard(Bitmap bitmap, String filename) {
String stored = null;
File sdcard = Environment.getExternalStorageDirectory();
File folder = new File(sdcard.getAbsoluteFile(), ".tam");//the dot makes this directory hidden to the user
folder.mkdir();
File file = new File(folder.getAbsoluteFile(), filename) ;
if (file.exists())
return stored ;
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
stored = "success";
} catch (Exception e) {
e.printStackTrace();
}
return stored;
}
public static File getImage(String imagename) {
File mediaImage = null;
try {
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
File myDir = new File(root);
if (!myDir.exists())
return null;
mediaImage = new File(myDir.getPath() + "/.tam/"+imagename);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mediaImage;
}
public static File checkifImageExists(String imagename) {
File file = ImageStorage.getImage("/" + imagename);
if (file.exists()) {
return file;
} else {
return null;
}
}
public static String getImageName(String value){
String getName[] = value.split("/");
return getName[4];
}
}
Below path not in all mobile:
/storage/emulated/0/
Thanks in advance!!
Maybe u should check if there's external storage in the mobile before u use this path
public String getDir(Context context) {
String checkPath = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
|| !Environment.isExternalStorageRemovable()) {
checkPath = Environment.getExternalStorageDirectory().getPath();
} else {
checkPath = context.getCacheDir().getPath();
}
return checkPath;
}
In reality its just making a copy of a text.txt file. I know how to use file chooser to choose the file but that is as far as my knowledge really goes.
I can do this:
public BasicFile()
{
JFileChooser choose = new JFileChooser(".");
int status = choose.showOpenDialog(null);
try
{
if (status != JFileChooser.APPROVE_OPTION) throw new IOException();
f = choose.getSelectedFile();
if (!f.exists()) throw new FileNotFoundException();
}
catch(FileNotFoundException e)
{
display(1, e.toString(), "File not found ....");
}
catch(IOException e)
{
display(1, e.toString(), "Approve option was not selected");
}
}
Path object is perfect for copying files,
Try this code to copy a file,
Path source = Paths.get("c:\\blabla.txt");
Path target = Paths.get("c:\\blabla2.txt");
try {
Files.copy(source, target);
} catch (IOException e1) {
e1.printStackTrace();
}
If you have to backup a whole folder, you can use this code
public class BackUpFolder {
public void copy(File sourceLocation, File targetLocation) throws IOException {
if (sourceLocation.isDirectory()) {
copyDirectory(sourceLocation, targetLocation);
} else {
copyFile(sourceLocation, targetLocation);
}
}
private void copyDirectory(File source, File target) throws IOException {
if (!target.exists()) {
target.mkdir();
}
for (String f : source.list()) {
copy(new File(source, f), new File(target, f));
}
}
private void copyFile(File source, File target) throws IOException {
try (
InputStream in = new FileInputStream(source);
OutputStream out = new FileOutputStream(target)) {
byte[] buf = new byte[1024];
int length;
while ((length = in.read(buf)) > 0) {
out.write(buf, 0, length);
}
}
}
public static void main(String[] args) {
try {
BackUpFolder backUpFolder = new BackUpFolder();
String location = "./src/edu/abc/locationFiles/daofile"; //File path you are getting from file chooser
String target = "./src"; //target place you want to patse
File locFile = new File(location);
File tarFile = new File(target);
backUpFolder.copyDirectory(locFile, tarFile);
} catch (IOException ex) {
Logger.getLogger(BackUpFolder.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Start by taking a look at Basic I/O, which explains the basics of Input/OutputStreams and Readers and Writers, which are used to read/write bytes of data from a source to a destination.
If you're using Java 7 or over, you should also take a look at Copying a File or Directory which is part of newer Files and Paths API, which you can find more information about at File I/O (Featuring NIO.2)
I'm taking HTML file and one XSLT file as input and generating HTML output but in my folder there are multiple HTML files and I've to take each of them as input and generate the corresponding output file while XSLT input file remains same every time. Currently in my code I'm repeating the code block every time to take the input HTML file. Instead of this I want to iterate over all the HTML files in the folder and take them as input file one by one to generate the output. In my current code file names are also fixed like part_1.html but it can vary and in that case this code won't work and this will create problem. Can anyone please help out in this matter:
Thanking you!
Current Java code (Sample for two files):
public void tranformation() {
// TODO Auto-generated method stub
transform1();
transform2();
}
public static void transform1(){
String inXML = "C:/SCORM_CP/part_1.html";
String inXSL = "C:/source/xslt/html_new.xsl";
String outTXT = "C:/SCORM_CP/part1_copy_copy.html";
String renamedFile = "C:/SCORM_CP/part_1.html";
File oldfile =new File(outTXT);
File newfile =new File(renamedFile);
HTML_Convert hc = new HTML_Convert();
try {
hc.transform(inXML,inXSL,outTXT);
} catch(TransformerConfigurationException e) {
System.err.println("Invalid factory configuration");
System.err.println(e);
} catch(TransformerException e) {
System.err.println("Error during transformation");
System.err.println(e);
}
try{
File file = new File(inXML);
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
if(oldfile.renameTo(newfile)){
System.out.println("Rename succesful");
}else{
System.out.println("Rename failed");
}
}
public static void transform2(){
String inXML = "C:/SCORM_CP/part_2.html";
String inXSL = "C:/source/xslt/html_new.xsl";
String outTXT = "C:/SCORM_CP/part2_copy_copy.html";
String renamedFile = "C:/SCORM_CP/part_2.html";
File oldfile =new File(outTXT);
File newfile =new File(renamedFile);
HTML_Convert hc = new HTML_Convert();
try {
hc.transform(inXML,inXSL,outTXT);
} catch(TransformerConfigurationException e) {
System.err.println("Invalid factory configuration");
System.err.println(e);
} catch(TransformerException e) {
System.err.println("Error during transformation");
System.err.println(e);
}
try{
File file = new File(inXML);
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
if(oldfile.renameTo(newfile)){
System.out.println("Rename succesful");
}else{
System.out.println("Rename failed");
}
}
public void transform(String inXML,String inXSL,String outTXT)
throws TransformerConfigurationException,
TransformerException {
TransformerFactory factory = TransformerFactory.newInstance();
StreamSource xslStream = new StreamSource(inXSL);
Transformer transformer = factory.newTransformer(xslStream);
transformer.setErrorListener(new MyErrorListener());
StreamSource in = new StreamSource(inXML);
StreamResult out = new StreamResult(outTXT);
transformer.transform(in,out);
System.out.println("The generated XML file is:" + outTXT);
}
}
File dir = new File("/path/to/dir");
File[] htmlFiles = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.endsWith(".html");
}
});
if (htmlFiles != null) for (File html: htmlFiles) {
...
}
You have to implement something like
public class Transformation {
public static void main (String[] args){
transformation(".", ".");
}
public static void transform(String inXML, String inXSL, String outTXT, String renamedFile){
System.out.println(inXML);
System.out.println(inXSL);
System.out.println(outTXT);
System.out.println(renamedFile);
}
public static void transformation(String inFolder, String outFolder){
File infolder = new File(inFolder);
File outfolder = new File(outFolder);
if (infolder.isDirectory() && outfolder.isDirectory()){
System.out.println("In " + infolder.getAbsolutePath());
System.out.println("Out " + outfolder.getAbsolutePath());
File[] listOfFiles = infolder.listFiles();
String outPath = outfolder.getAbsolutePath();
String inPath = infolder.getAbsolutePath();
for (File f: listOfFiles) {
if (f.isFile() ) {
System.out.println("File " + f.getName());
int indDot = f.getName().lastIndexOf(".");
String name = f.getName().substring(0, indDot);
String ext = f.getName().substring(indDot+1);
if (ext != null && ext.equals("html")){
transform(f.getAbsolutePath(), inPath+File.separator+name+".xsl", outPath+File.separator+name+".txt", outPath+File.separator+name+".html");
}
}
}
}
}
}
First you should write a method that take inXML, inXSL, outTXT and renamedFile as arguments.
Then, using the list() method of the File class, that eventually take a FilenameFilter, you may iterate over the files you want to transform.
Here is a sample of FilenameFilter :
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.contains("part");
}
};
Regards
use DirectoryScanner which will make your job easier
Example of usage:
String[] includes = {"**\*.html"};
ds.setIncludes(includes);
ds.setBasedir(new File("test"));
ds.setCaseSensitive(true);
ds.scan();
System.out.println("FILES:");
String[] files = ds.getIncludedFiles();
for (int i = 0; i < files.length; i++) {
System.out.println(files[i]);
}
http://plexus.codehaus.org/plexus-utils/apidocs/org/codehaus/plexus/util/DirectoryScanner.html