import java.io.File
import java.io.FileReader
import java.io.FileWriter
import java.io.IOException
public class IOTest {
public static void main(String[] args) {
String str = "123\r\n456"
writeFile(str)//写
String str1 = readFile()//读
System.out.println(str1)
}
/**
* 传递写的内容
* @param str
*/
static void writeFile(String str) {
try {
File file = new File("d:\\file.txt")
if(file.exists()){//存在
file.delete()//删除再建
file.createNewFile()
}else{
file.createNewFile()//不存在直接创建
}
FileWriter fw = new FileWriter(file)//文件写IO
fw.write(str)
fw.flush()
fw.close()
} catch (IOException e) {
e.printStackTrace()
}
}
/**
* 返回读取的内容
* @return
*/
static String readFile() {
String str = "", temp = null
try {
File file = new File("d:\\file.txt")
FileReader fr = new FileReader(file)
BufferedReader br = new BufferedReader(fr)//文件读IO
while((temp = br.readLine())!=null){//读到结束为止
str += (temp+"\n")
}
br.close()
fr.close()
} catch (IOException e) {
e.printStackTrace()
}
return str
}
}
刚写的,够朋友好好学习一下啦,呵呵
多多看API,多多练习
import java.io.Fileimport java.io.FileNotFoundException
import java.io.IOException
import java.io.RandomAccessFile
public class Io{
public static void main(String [] s){
File filename = new File("F:\\suncity.txt")
String filein="你好!"
RandomAccessFile mm = null
try {
mm = new RandomAccessFile(filename,"rw")
mm.writeBytes(filein)
} catch (IOException e1) {
// TODO 自动生成 catch 块
e1.printStackTrace()
} finally{
if(mm!=null){
try {
mm.close()
} catch (IOException e2) {
// TODO 自动生成 catch 块
e2.printStackTrace()
}
}
}
}
}
Java代码:import java.io.File
import java.io.IOException
public class Test10 {
public static void main(String[] args) {
//创建“abc”文件夹
String pathName = "d:\\abc"
File path = new File(pathName)
path.mkdir()
//创建“abc”文件
String fileName = "d:\\abc\\abc"
File file = new File(fileName)
try {
file.createNewFile()
}
catch (IOException e) {
e.printStackTrace()
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)