当你获得FileOutput对象时,写入具体的目录就可以了。
比如:你要写入到D:\java\test目录下。
方法一:
方法二:
比如:你要写入到D:\java\test目录下。
方法一:
- String name = "out.html";
- String dir = "D:\\java\\test";
- File file = new File(dir,name);
- FileOutputStream out = new FileOutputStream(file);
- FileOutputStream out = new FileOutputStream(dir+"\\"+name);
实现换行
第一种:
写入的内容中利用\r\n进行换行
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
File file =
new
File(
"D:/text"
);
try
{
if
(!file.exists())
file.createNewFile();
FileOutputStream out=
new
FileOutputStream(file,
false
);
StringBuffer sb=
new
StringBuffer();
sb.append(
"10600257100120161201153103010 \r\n"
);
sb.append(
"120161201KBS571009886631浙江目录上传120161201094425210009302359591120110422KBS00005595530ZZA571ZZA20161201094435fanzhipeng2000\n"
);
out.write(sb.toString().getBytes(
"utf-8"
));
//注意需要转换对应的字符集
out.flush();
out.close();
/*<br> FileOutputStream out =
new
FileOutputStream(file); <br> BufferedWriter writer =
new
BufferedWriter(
new
OutputStreamWriter(writerStream,
"UTF-8"
)); <br> writer.write(json);<br> writer.close();
|
1
2
3
4
5
|
<em id=
"__mceDel"
> */<br>
}
catch
(IOException e) {
e.printStackTrace();
}
</em>
|
第二种:
利用BufferedWriter的newline()方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
File file =
new
File(
"D:/text"
);
try
{
if
(!file.exists())
file.createNewFile();
FileWriter out=
new
FileWriter (file);
BufferedWriter bw=
new
BufferedWriter(out);
bw.write(
"10600257100120161201153103010 "
);
bw.newLine();
bw.write(
"120161201KBS571009886631浙江目录上传120161201094425210009302359591120110422KBS00005595530ZZA571ZZA20161201094435fanzhipeng2000"
);
bw.newLine();
bw.flush();
bw.close();
}
catch
(IOException e) {
e.printStackTrace();
}
|
但是newLine在使用中可能会出现问题:
不同系统的换行符:
windows --> \r\n
Linux --> \r
mac --> \n
我们一般开发是在 windows 下开发,而服务器一般情况下都是 linux。
如果我们使用 newline 函数换行,在本机测试的时候,因为是 windows 环境,换行符是 \r\n ,打开文件时候自然文件是换行处理,没有问题。
当我们部署到服务器时候,服务器是 linux 环境,newline 读取系统换行符是 \r ,导出到文件,文件的换行符是 \r,当我们把这个文件通过浏览器下载到 windows 时候,再打开文件将会出现没有换行的问题。因为 windows 下对于 \r 的解释并不是换行符。
所以,我们在开发时候,如果需要指定文件在某些地方换行,则不能使用 newline 方法。必须手动指定换行符:\r\n 因为按照上面列举的不同系统换行符看,如果字符串的末尾是 \r\n 在三个系统中,查看该文件,都会解释为换行。