我正在尝试创建一个应用程序,允许我将mp3和mp4文件从一个目录复制到另一个目录我正在使用文件选择器和工厂模式。该文件似乎复制到该位置但不会播放。新文件是8k而原始mp3是8mb所以我猜它从未复制过内容,只是创建了文件。
这是我的Mp3Factory
课程:
package application;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import javafx.scene.media.Media;
public class Mp3Factory extends MediaFactory{
private File folder = null;
private File file= null;
private Media m = null;
FileOutputStream output = null;
@Override
public File openFile() {
//Add image filter to file chooser
fc.addChoosableFileFilter(new FileNameExtensionFilter("Mp3 Files", "mp3"));
fc.setAcceptAllFileFilterUsed(false);
//Show the file chooser dialog
int returnVal = fc.showOpenDialog(null);
//If the user chose a file then return it
if (returnVal == JFileChooser.APPROVE_OPTION) {
return fc.getSelectedFile();
} else {
System.out.println("Open command cancelled by user.");
return null;
}
}
@Override
public void saveFile(File file) {
String fileName = file.getName();
folder = new File("H:\\TestFolder\\"); //output file path
if (!folder.exists()) {
try {
folder.createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}
}
try{
String folder_location = folder.toString() + "\\";
file = new File(folder_location + fileName.toString());
output = new FileOutputStream(file);
if (!file.exists()) {
file.createNewFile();
}
byte[] buffer = new byte[4096];
output.write(buffer);
output.flush();
output.close();
}catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void defaultSavePath() {
// TODO Auto-generated method stub
}
@Override
public void loaddefaultSavePath() {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:4)
Java已经有了很好的复制功能:
public void saveFile(File file) throw IOException {
Path sourcePath = file.toPath();
String fileName = file.getName();
String targetPath = Paths.get("H:\\TestFolder", fileName);
Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
}
答案 1 :(得分:0)
package parse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class CopySong {
public static void main(String[] args) {InputStream inStream = null;
OutputStream outStream = null;
try{
File source =new File("D:\\A.mp3");
File dtn =new File("path\\A.mp3");
inStream = new FileInputStream(source);
outStream = new FileOutputStream(dtn);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
System.out.println("File is copied successful!");
}catch(IOException e){
e.printStackTrace();
}
}
}