当复制文件从一个位置改为另一个不工作时我的代码中的错误更改字节请帮助我,如果我删除字符串s1;然后它的工作完美只是重复原始文件当我使用s1字符串改变字节时它不起作用
samplet.text file contain numbers
3434214280
3044559080
3154356865
3312430124
3334491537
package com.example.copyfilefromdirectorytoanother;
ublic class MainActivity extends Activity {
private static final String TAG = "MainActivity.java";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// your sd card
String sdCard = Environment.getExternalStorageDirectory().toString();
// the file to be moved or copied
File sourceLocation = new File (sdCard + "/sample.txt");
// make sure your target location folder exists!
File targetLocation = new File (sdCard + "/MyNewFolder/sample.txt");
// just to take note of the location sources
Log.v(TAG, "sourceLocation: " + sourceLocation);
Log.v(TAG, "targetLocation: " + targetLocation);
try {
// 1 = move the file, 2 = copy the file
int actionChoice = 2;
// moving the file to another directory
if(actionChoice==1){
if(sourceLocation.renameTo(targetLocation)){
Log.v(TAG, "Move file successful.");
}else{
Log.v(TAG, "Move file failed.");
}
}
// we will copy the file
else{
// make sure the target file exists
if(sourceLocation.exists()){
InputStream in = new
FileInputStream(sourceLocation);
OutputStream out = new
FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
String s1;
// byte[] theByteArray ;
byte[] buf = new byte[1024];
byte[] theByteArray = new byte[1024];
int len;
int n =1;
while ((len = in.read(buf)) > 0) {
s1= "BEGIN:VCARD \n VERSION:2.1 \n N:;UNKNOWN "+n+";;; \n FN:UNKNOWN "+n+"
\n TEL;CELL;PREF:+92"+buf+" \n END:VCARD ";
theByteArray=s1.getBytes();
out.write(theByteArray, 0, len);
n=n+1;
}
in.close();
out.close();
Log.v(TAG, "Copy file successful.");
}else{
Log.v(TAG, "Copy file failed. Source file
missing.");
}
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
好吧,你正在读取len个字节,向它附加数据,然后写出len个字节。这是错的,你需要做out.write(theByteArray, 0, theByteArray.length);
我也可以看到其他可能存在的问题,但你的文件可能足够小以避免它们。