File copy from raw to External (secondary) SD card - java

I know that many question has been answered,
but in my case my code is working properly on Oppo, samsung phone but not work on MI, MOto G, Lenavo phone
Here is my code:
This String return path of secondary SD card:
public static String getExternalStorage() {
File rootFolder = new File("/");
boolean isSdcardRemovable = false;
String path = null;
/* loop: */
for (int i = 0; i < rootFolder.listFiles().length; i++) {
if (rootFolder.listFiles()[i].listFiles() != null
&& !rootFolder.listFiles()[i].toString().contains("system")
&& !rootFolder.listFiles()[i].toString().contains("etc")
&& !rootFolder.listFiles()[i].toString().contains("dev")) {
File dataDir = new File(Environment.getDataDirectory()
.getAbsolutePath());
long dataDirSize = dataDir.getFreeSpace() / (1000 * 1000);
long folderSize = rootFolder.listFiles()[i].getFreeSpace()
/ (1000 * 1000);
if (dataDirSize == folderSize
|| (dataDirSize > folderSize && folderSize > (dataDirSize - 80))) {
System.err
.println("INTERNAL1 " + rootFolder.listFiles()[i]);
System.err.println(dataDirSize);
System.err.println(folderSize);
} else {
File rootSubFolder1 = new File(
rootFolder.listFiles()[i].getAbsolutePath());
if (rootSubFolder1.listFiles() != null) {
for (int j = 0; j < rootSubFolder1.listFiles().length; j++) {
if (rootSubFolder1.listFiles()[j].getTotalSpace() != 0
&& rootSubFolder1.listFiles()[j]
.getFreeSpace() != 0
&& rootSubFolder1.listFiles()[j]
.listFiles() != null) {
Debug.i("fromGetExternalStorage", ""
+ rootSubFolder1.listFiles()[j]);
if (rootSubFolder1.listFiles()[j].toString()
.contains("sdcard")
|| rootSubFolder1.listFiles()[j]
.toString().contains("storage")
|| rootSubFolder1.listFiles()[j]
.toString().contains("mnt")) {
folderSize = rootSubFolder1.listFiles()[j]
.getFreeSpace() / (1000 * 1000);
if (dataDirSize == folderSize
|| (dataDirSize > folderSize && folderSize > (dataDirSize - 80))) {
System.err
.println("INTERNAL2 "
+ rootSubFolder1
.listFiles()[j]);
System.err.println(dataDirSize);
System.err.println(folderSize);
} else {
int pos = rootSubFolder1.listFiles()[j]
.getAbsolutePath().lastIndexOf(
'/');
String str = rootSubFolder1.listFiles()[j]
.getAbsolutePath().substring(
pos + 1);
if (str.matches("(sd|ext|3039|m_external_sd).*")) {
isSdcardRemovable = true;
System.err.println("EXTERNAL "
+ rootSubFolder1
.listFiles()[j]);
System.err.println(dataDirSize);
System.err.println(folderSize);
path = rootSubFolder1.listFiles()[j]
.getAbsolutePath() + "/";
break loop;
}
}
}
}
}
}
}
}
}
if (isSdcardRemovable) {
if (path != null) {
Debug.i("new Path from getExternal Storage", path);
} else {
Debug.i("fail", "External memory not found.");
}
} else {
Debug.i("fail", "External memory not available.");
}
return path;
}`
And This Code that I use path and copy file:
OutputStream OS = new FileOutputStream(path + File.separator + "name.txt");

First Make Directories
File wallpaperDirectory = new File("sdcard/Youpath/");
// have the object build the directory structure, if needed.
if(!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
Code to Copy
final int[] mList= new int[] { R.raw.a, R.raw.b, R.raw.c,R.raw.d,R.raw.e,R.raw.f,
R.raw.g,R.raw.h,R.raw.i,R.raw.j,R.raw.k,R.raw.l,R.raw.m,R.raw.n,R.raw.o,R.raw.p,R.raw.q
,R.raw.r,R.raw.s,R.raw.t,R.raw.u};
for (int i = 0; i < mList.length; i++) {
try {
String path = "sdcard/Youpath/";
File dir = new File(path);
if (dir.mkdirs() || dir.isDirectory()) {
String mName= "YourSetName"+ String.valueOf(i+1) + ".extension";
CopyRAWtoSDCard(mList[i], path + File.separator + mName);
}
} catch (IOException e) {
e.printStackTrace();
}
}
CopyRAWtoSDCard Function
private void CopyRAWtoSDCard(int id, String path) throws IOException {
InputStream in = getResources().openRawResource(id);
FileOutputStream out = new FileOutputStream(path);
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
} finally {
in.close();
out.close();
}
}

Related

Video bad quality when play in java

I am trying to play a video in Java using xuggler, but when I run it the quality significantly decreases. Here are 2 screenshots as an example:
From the second screenshot you can see the colors are all different. I am not a video expert, could someone tell me where is the problem? Video decoder? Color encoding? Can someone help me?
EDIT: this is the code I wrote to play the video. It is the same as Xuggler's example.
if (container.open("temp.flv",IContainer.Type.READ,null) < 0) {
throw new IllegalArgumentException("could not open file: " + whatToPlay);
}
int numStreams = container.getNumStreams();
int videoStreamId = -1;
int audioStreamId = -1;
for (int i = 0; i < numStreams; i++) {
IStream stream = container.getStream(i);
IStreamCoder coder = stream.getStreamCoder();
if (coder.getCodecType() == ICodec.Type.CODEC_TYPE_VIDEO) {
videoStreamId = i;
videoCoder = coder;
}
if (coder.getCodecType() == ICodec.Type.CODEC_TYPE_AUDIO) {
audioStreamId = i;
audioCoder = coder;
}
}
if (videoStreamId == -1 && audioStreamId == -1) {
throw new RuntimeException("could not find audio or video stream in container: " + whatToPlay);
}
if(videoCoder != null) {
if (videoCoder.open() < 0) {
throw new RuntimeException("could not open video decoder for container: " + whatToPlay);
}
}
if(audioCoder != null) {
if(audioCoder.open() < 0) {
throw new RuntimeException("could not open audio decoder for container: " + whatToPlay);
}
try {
openJavaSound(audioCoder);
} catch(LineUnavailableException reason) {
throw new RuntimeException("unable to open sound device on your system when playing back container: " + whatToPlay);
}
}
IVideoResampler resampler = null;
if (videoCoder.getPixelType() != IPixelFormat.Type.BGR24) {
resampler = IVideoResampler.make(videoCoder.getWidth(),
videoCoder.getHeight(), IPixelFormat.Type.BGR24,
videoCoder.getWidth(), videoCoder.getHeight(), videoCoder.getPixelType());
if (resampler == null) {
throw new RuntimeException("could not create color space resampler for: " + whatToPlay);
}
}
IPacket packet = IPacket.make();
while (container.readNextPacket(packet) >= 0) {
if (packet.getStreamIndex() == audioStreamId) {
IAudioSamples samples = IAudioSamples.make(1024, audioCoder.getChannels());
int offset = 0;
while (offset < packet.getSize()) {
int bytesDecoded = audioCoder.decodeAudio(samples, packet, offset);
if (bytesDecoded < 0) {
throw new RuntimeException("got error decoding audio in: " + whatToPlay);
}
offset += bytesDecoded;
if (samples.isComplete() && (isMute == false)) {
playJavaSound(samples);
}
}
} else if (packet.getStreamIndex() == videoStreamId) {
picture = IVideoPicture.make(videoCoder.getPixelType(), videoCoder.getWidth(), videoCoder.getHeight());
int offset = 0;
while (offset < packet.getSize()) {
int bytesDecoded = videoCoder.decodeVideo(picture, packet, offset);
offset += bytesDecoded;
if (picture.isComplete()) {
IVideoPicture newPic = picture;
if (resampler != null) {
// we must resample
newPic = IVideoPicture.make(resampler.getOutputPixelFormat(), picture.getWidth(), picture.getHeight());
if (resampler.resample(newPic, picture) < 0) {
throw new RuntimeException("could not resample video from: " + whatToPlay);
}
}
if (newPic.getPixelType() != IPixelFormat.Type.BGR24) {
throw new RuntimeException("could not decode video as BGR 24 bit data in: " + whatToPlay);
}
updatePanelImage(Utils.videoPictureToImage(newPic));
}
}
} else {
do {
} while (false);
}
}

Exception shoutcast and java

I trying to write a code to stream from shoutcast server
and I use the below code and give me javax.sound.sampled.UnsupportedAudioFileException
how I can solve the exception
public static void streamSampledAudio(URL url)
throws IOException, UnsupportedAudioFileException,
LineUnavailableException
{
AudioInputStream ain = null; // We read audio data from here
SourceDataLine line = null; // And write it here.
try {
InputStream is = url.openStream();
BufferedInputStream bis = new BufferedInputStream( is );
ain=AudioSystem.getAudioInputStream(bis);
AudioFormat format = ain.getFormat( );
DataLine.Info info=new DataLine.Info(SourceDataLine.class,format);
if (!AudioSystem.isLineSupported(info)) {
AudioFormat pcm =
new AudioFormat(format.getSampleRate( ), 16,
format.getChannels( ), true, false);
ain = AudioSystem.getAudioInputStream(pcm, ain);
format = ain.getFormat( );
info = new DataLine.Info(SourceDataLine.class, format);
}
line = (SourceDataLine) AudioSystem.getLine(info);
line.open(format);
int framesize = format.getFrameSize( );
byte[ ] buffer = new byte[4 * 1024 * framesize]; // the buffer
int numbytes = 0; // how many bytes
boolean started = false;
for(;;) { // We'll exit the loop when we reach the end of stream
int bytesread=ain.read(buffer,numbytes,buffer.length-numbytes);
if (bytesread == -1) break;
numbytes += bytesread;
if (!started) {
line.start( );
started = true;
}
int bytestowrite = (numbytes/framesize)*framesize;
line.write(buffer, 0, bytestowrite);
int remaining = numbytes - bytestowrite;
if (remaining > 0)
System.arraycopy(buffer,bytestowrite,buffer,0,remaining);
numbytes = remaining;
}
line.drain( );
}
finally { // Always relinquish the resources we use
if (line != null) line.close( );
if (ain != null) ain.close( );
}
}
and give me an exception
Exception in thread "main" javax.sound.sampled.UnsupportedAudioFileException: could not get audio
input stream from input stream
at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
at test.PlaySoundStream.streamSampledAudio(PlaySoundStream.java:40)
at test.PlaySoundStream.main(PlaySoundStream.java:21)
can help me to solve the exception
or tell me about away can stream by it from shoutcast
I try this code to download MP3 from shoutcast and then you can play sound
public class DownloadMP3 {
private boolean halt = false;
public static final String DEFAULT_HOST = "127.0.0.1";
protected String host = "url";
public static final int DEFAULT_PORT = 80;
protected int port = 8568;
public static final int DEFAULT_TOTAL_SIZE = 0;
protected long totalSize = 0L;
public static final int DEFAULT_CHUNK_SIZE = 0;
long chunkSize = 0L;
public static final String DEFAULT_OUTPUT_DIRECTORY = ".";
File outputDirectory = new File("D:\\");
public static void main(String[ ] args) throws Exception {
DownloadMP3 d = new DownloadMP3();
d.run();
}
public void run()
{
Socket localSocket = null;
PrintWriter localPrintWriter = null;
BufferedInputStream localBufferedInputStream = null;
FileOutputStream localFileOutputStream = null;
try
{
writeMessage("Opening connection to " + this.host + ":" + this.port);
localSocket = new Socket(this.host, this.port);
localPrintWriter = new PrintWriter(localSocket.getOutputStream(), true);
localBufferedInputStream = new BufferedInputStream(localSocket.getInputStream());
localPrintWriter.print("GET / HTTP/1.0\r\n\r\n");
localPrintWriter.flush();
byte[] arrayOfByte = new byte[1024];
long l1 = 0L;
long l2 = 0L;
int i = 1;
File localFile = null;
writeMessage("Host contacted, waiting for response...");
try
{
int k = 0;
int m;
writeMessage("Recieving Data....");
int j;
while ((j = localBufferedInputStream.read(arrayOfByte)) != -1) {
if ((localFileOutputStream == null) || ((this.chunkSize > 0L) && (l2 + j >= this.chunkSize))) {
m = findSync(arrayOfByte, 0, j);
if (m == -1) {
m = j;
}
if (localFileOutputStream != null)
{
localFileOutputStream.write(arrayOfByte, 0, m);
}
if (localFileOutputStream != null) {
localFileOutputStream.close();
}
while ((localFile = new File(this.outputDirectory, this.host + '-' + this.port + '-' + formatFileNum(i++) + ".mp3")).exists());
writeMessage("Saving to file: " + localFile);
localFileOutputStream = new FileOutputStream(localFile);
l2 = 0L;
localFileOutputStream.write(arrayOfByte, m, j - m);
l2 += j - m;
} else {
localFileOutputStream.write(arrayOfByte, 0, j);
l2 += j;
}
if ((this.totalSize > 0L) && (l1 >= this.totalSize)) {
writeMessage("Capture completed successfully.");
if (this.halt) {
writeMessage("Capture interruted.");
}
}
writeErrorMessage("Connection closed by host.");
return;
} catch (IOException localIOException2) {
if (this.halt)
writeMessage("Capture interruted.");
else {
writeErrorMessage(localIOException2.getMessage());
}
} finally {
if (localFileOutputStream != null)
localFileOutputStream.close();
}
}
catch (UnknownHostException localUnknownHostException) {
writeErrorMessage("Unknown host: " + this.host);
return;
} catch (IOException localIOException1) {
writeErrorMessage("Could not connect to " + this.host + " on port " + this.port);
}
finally {
if (localPrintWriter != null) {
localPrintWriter.close();
}
if (localBufferedInputStream != null)
try {
localBufferedInputStream.close();
}
catch (IOException localIOException3) {
}
if (localSocket != null)
try {
localSocket.close();
}
catch (IOException localIOException4)
{
}
}
}
private static int findSync(byte[] paramArrayOfByte, int paramInt1, int paramInt2)
{
for (int i = paramInt1; i < paramInt2 - 1; i++) {
if (((paramArrayOfByte[i] & 0xFF) == 255) && ((paramArrayOfByte[(i + 1)] & 0xE0) == 224)) {
return i;
}
}
return -1;
}
private static String formatFileNum(int paramInt)
{
if (paramInt < 10)
return "00" + paramInt;
if (paramInt < 100) {
return "0" + paramInt;
}
return "" + paramInt;
}
protected void writeMessage(String paramString)
{
System.out.println(paramString);
}
protected void writeErrorMessage(String paramString)
{
System.err.println(paramString);
}
}

Extracting files from Oracle blob fields;

I am trying to extract a file from a blob using the values found in the fields following the blob column. My solution works, but it is rather slow.
I extracted 169MB(727 different files) in about 1 hour. That's about 12 files a minute.
most of the files are usually between 5KB and 50KB but can sometimes be as big as 2MB. I am working with a local Oracle database.
Is there anything I could do to make my code more efficient? If not, what other factors might affect the speed of the process? Here is the method's code:
public void beginExtraction(String FileOutDir, String blobSQL,
String fileSuffix, Connection conn) {
if ((FileOutDir != null) && (blobSQL != null) && (conn != null)) {
PreparedStatement selBlobs = null;
FileOutputStream fos = null;
if (conn != null) {
if (blobSQL != null) {
try {
selBlobs = conn.prepareStatement(blobSQL);
ResultSet rs = selBlobs.executeQuery();
int cols = rs.getMetaData().getColumnCount();
while (rs.next()) {
Blob blob = rs.getBlob(1);
InputStream is = blob.getBinaryStream();
String filepath = "";
filepath += FileOutDir + "/";
for (int c = 2; c <= cols; c++) {
filepath += rs.getObject(c).toString() + "_";
}
filepath = filepath.substring(0,
filepath.length() - 1);
filepath += fileSuffix;
fos = new FileOutputStream(filepath);
int b = 0;
while ((b = is.read()) != -1) {
fos.write(b);
}
}
selBlobs.close();
fos.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(gui, e.toString());
}
}
}
} else {
if (conn == null) {
JOptionPane.showMessageDialog(gui,
"You have not selected a database.");
} else {
if (FileOutDir == null) {
JOptionPane.showMessageDialog(gui,
"You have not chosen a directory for your files.");
} else {
if (blobSQL == null) {
JOptionPane.showMessageDialog(gui,
"Please insert an SQL statement.");
}
}
}
}
}
Changing to a buffered output made the process exponentially faster. I was able to export the 727 files in under a minute. Here the new code:
//...
while (rs.next()) {
blob = rs.getBlob(1);
is = blob.getBinaryStream();
filepath += "/";
for (int c = 2; c <= cols; c++) {
filepath += rs.getObject(c).toString() + "_";
}
filepath = filepath.substring(0,
filepath.length() - 1);
filepath += fileSuffix;
fos = new BufferedOutputStream(new FileOutputStream(filepath));
while ((b = is.read()) != -1) {
fos.write(b);
}
filepath = FileOutDir;
b = 0;
}
//...

I can't manage to copy files from assets to external storage

I am making an Android application, and I would like to add two files named fsx.xml and xplane.xml. This is the code I am using, it runs perfectly without errors, but the /planesim just appears empty. Please help!
String planesimFolderName = "/planesim";
String fsxFile = "fsx.xml";
String xplaneFile = "xplane.xml";
String asset;
File assetDestination;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
final File planesimFolder = new File(Environment.getExternalStorageDirectory() + planesimFolderName);
final AssetManager assetManager = getAssets();
for (int fileCount = 1; fileCount == 2; fileCount++) {
if (fileCount == 1) {
asset = fsxFile;
} else if (fileCount == 2) {
asset = xplaneFile;
}
assetDestination = new File(Environment.getExternalStorageDirectory() + planesimFolderName + "/" + asset);
try {
InputStream in = assetManager.open(asset);
FileOutputStream f = new FileOutputStream(assetDestination);
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
Log.d("CopyFileFromAssetsToSD", e.getMessage());
}
}
}
Thanks for your time and help, zeokila.
This is your mistake:
for (int fileCount = 1; fileCount == 2; fileCount++)
which is like:
int fileCount = 1;
while(fileCount == 2) // never true...
The for loop never executed (because 1 != 2), should be:
for (int fileCount = 1; fileCount <= 2; fileCount++)

Xuggle combine audio with generated audio

I have an mp3 file, and an image. I need to create a video combining them, in java.
I'm trying to do it with xuggle, but there are still no results.
Can anybody give me any suggestions ?
Finally, I found a solution.
I used pieces of code from Xuggle's examples.
I also solved a problem with audio transcoding.
I'll write my code here, because I cannot explain why it works, but it just works.
public String make() throws IOException, InterruptedException {
BufferedImage s1 = genImage();
writer = ToolFactory.makeWriter("temp/" + sermon.getFile().getName() + ".flv");
String filename = sermon.getFile().getAbsolutePath();
IContainer container = IContainer.make();
if (container.open(filename, IContainer.Type.READ, null) < 0) {
throw new IllegalArgumentException("could not open file: " + filename);
}
int numStreams = container.getNumStreams();
int audioStreamId = -1;
IStreamCoder audioCoder = null;
for (int i = 0; i < numStreams; i++) {
IStream stream = container.getStream(i);
IStreamCoder coder = stream.getStreamCoder();
if (coder.getCodecType() == ICodec.Type.CODEC_TYPE_AUDIO) {
audioStreamId = i;
audioCoder = coder;
break;
}
}
if (audioStreamId == -1) {
throw new RuntimeException("could not find audio stream in container: " + filename);
}
if (audioCoder.open() < 0) {
throw new RuntimeException("could not open audio decoder for container: " + filename);
}
writer.addAudioStream(0, 0, audioCoder.getChannels(), audioCoder.getSampleRate());
writer.addVideoStream(1, 1, width, height);
IPacket packet = IPacket.make();
int n = 0;
while (container.readNextPacket(packet) >= 0) {
n++;
if (packet.getStreamIndex() == audioStreamId) {
IAudioSamples samples = IAudioSamples.make(2048, audioCoder.getChannels());
int offset = 0;
while (offset < packet.getSize()) {
try {
int bytesDecoded = audioCoder.decodeAudio(samples, packet, offset);
if (bytesDecoded < 0) {
//throw new RuntimeException("got error decoding audio in: " + filename);
break;
}
offset += bytesDecoded;
if (samples.isComplete()) {
if (n % 1000 == 0) {
writer.flush();
System.out.println(n);
System.gc();
}
writer.encodeAudio(0, samples);
}
} catch (Exception e) {
System.out.println(e);
}
}
} else {
do {
} while (false);
}
}
for (int i = 0; i < container.getDuration() / 1000000; i++) {
writer.encodeVideo(1, s1, i, TimeUnit.SECONDS);
}
writer.close();
if (audioCoder != null) {
audioCoder.close();
audioCoder = null;
}
if (container != null) {
container.close();
container = null;
}
return "temp/" + sermon.getFile().getName() + ".flv";
}
Thanks, good luck.

Categories

Resources