import java.io.File
import java.io.FileNotFoundException
import java.util.Scanner
public class ReadFile {
public static String getFile(String realpath) {
Scanner scanner = null
String text = ""
try {
File file= new File(realpath)
scanner = new Scanner(file)
} catch (FileNotFoundException e) {
e.printStackTrace()
}
if(scanner!=null){
while(scanner.hasNextLine()){
text+=scanner.nextLine()
}
scanner.close()
}
//System.out.println(text)
return text
}
static class InnerTest{
public static void main(String[] args) {
String realpath = "D:\\test.txt"
String text=getFile(realpath)
System.out.println(text)
}
}
}
实现方式有很多,还可以用字节流FileInputStream,字符流FileReader等方式读取
//根据你的要求修改了一下代码,现在已经能将某文件夹下的所有指定类型文件复制到//指定文件夹下了
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
public class ReadFiles {
public static final String FILTER = "xml"
public static final String SRC_DIR = "E:\\StudyData"// 待扫描的文件夹
public static final String DES_DIR = "E:\\testdata"// 复制后的目标文件夹
public static void main(String[] args) {
long a = System.currentTimeMillis()
scanDir(SRC_DIR, DES_DIR)
System.out.println("共花费时间:"+(System.currentTimeMillis() - a)/1000+"秒")
}
public static void scanDir(String srcPath, String desPath) {
File dir = new File(srcPath)
File[] files = dir.listFiles()
if (files == null)
return
for (int i = 0i <files.lengthi++) {
if (files[i].isDirectory()) {
scanDir(files[i].getAbsolutePath(), desPath)
} else {
String strFileName = files[i].getAbsolutePath().toLowerCase()
copyFile(strFileName, desPath + files[i].getName())
}
}
}
public static void copyFile(String srcName, String destName) {
if (srcName.endsWith(FILTER)) {
System.out.println("正在复制文件 "+srcName+" 至 "+destName)
try {
BufferedInputStream in = new BufferedInputStream(
new FileInputStream(srcName))
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(destName))
int i = 0
byte[] buffer = new byte[2048]
while ((i = in.read(buffer)) != -1) {
out.write(buffer, 0, i)
}
out.close()
in.close()
} catch (Exception ex) {
ex.printStackTrace()
}
}
}
}
public class Test {public static void main(String[] args) {
readFileByChars("d://test.txt")
}
public static void readFileByChars(String fileName) {
File file = new File(fileName)
Reader reader = null
try {
if (file!=null) {
// 一次读多个字符
char[] tempchars = new char[30]
int charread = 0
reader = new InputStreamReader(new FileInputStream(fileName))
// 读入多个字符到字符数组中,charread为一次读取字符数
while ((charread = reader.read(tempchars)) != -1) {
// 同样屏蔽掉\r不显示
if ((charread == tempchars.length)
&&(tempchars[tempchars.length - 1] != '\r')) {
System.out.print(tempchars)
} else {
for (int i = 0i <charreadi++) {
if (tempchars[i] == '\r') {
continue
} else {
System.out.print(tempchars[i])
}
}
}
}
}
} catch (Exception e1) {
e1.printStackTrace()
} finally {
if (reader != null) {
try {
reader.close()
} catch (IOException e1) {
System.out.println("文件不存在")
}
}
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)