import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Java从文件中获取路径,拷贝文件 在sts的maven工程中想要拷贝Maven引用的jar包。右键复制路径保存到文件,然后。。
*
* @author Administrator
*
*/
public class Test {
public static void main(String[] args) throws Exception {
byte[] data=readFromFile(new File("d:/test.txt"));
System.out.println(new String(data));
String filepath = "d:/fuck.txt";
String outputDir = "";
if (args.length != 2) {
System.out.println("usage: Test filepath outputdir");
return;
}
filepath = args[0];
outputDir = args[1];
BufferedReader reader = new BufferedReader(new FileReader(filepath));
List<String> filePaths = new ArrayList<String>();
String line = null;
while ((line = reader.readLine()) != null) {
filePaths.add(line);
}
reader.close();
File outputFile = new File(outputDir);
if (!outputFile.exists()) {
outputFile.mkdirs();
}
for (String string : filePaths) {
File file = new File(string);
if (file.exists() && file.getName().indexOf("eclipse") == -1) {
copyFile(file, outputDir);
}
}
}
private static void copyFile(File file, String outputDir) throws Exception {
FileInputStream fileInputStream = new FileInputStream(file);
FileOutputStream fileOutputStream = new FileOutputStream(new File(outputDir, file.getName()));
byte[] buffer = new byte[1024];
int len = -1;
while ((len = fileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, len);
}
fileOutputStream.flush();
fileOutputStream.close();
fileInputStream.close();
}
private static void writeToFile(File file, String content) throws Exception {
FileOutputStream fileOutputStream = new FileOutputStream(file);
byte[] buffer = content.getBytes();
fileOutputStream.write(buffer, 0, buffer.length);
fileOutputStream.flush();
fileOutputStream.close();
}
private static void writeToFileByText(File file, String content) throws Exception {
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(content);
fileWriter.flush();
fileWriter.close();
}
public static byte[] readFromFile(File file) {
try {
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[1024];
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int len = -1;
while ((len = fileInputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, len);
}
byteArrayOutputStream.flush();
byteArrayOutputStream.close();
fileInputStream.close();
return byteArrayOutputStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
Java从文件中获取路径,拷贝文件,读取文件和写入文件
最新推荐文章于 2022-08-01 17:58:37 发布