![](/img/trans.png)
[英]Unable to Write Contents of Jar File to Local Servlet on Tomcat 7.0.22
[英]Unable to write contents of file
package employee;
import employee.nidhin.staples;
import java.util.*;
import java.io.*;
public class Employee {
public static void main(String[] args)
{
int j=3;
staples[] stemp = new staples[j];
String file_name = "d:/personal/11636470/NetBeansProjects/Employee/src/employee/Xanadu.txt";
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
for ( j=0;j<3;j++)
{
stemp[j] = new staples();
System.out.print("Enter your name : ");
stemp[j].setName(reader.readLine());
System.out.println("Enter your age : ");
stemp[j].setAge(Integer.parseInt(reader.readLine()));
}
for ( j=0;j<3;j++)
{
System.out.println("Employee number:" + j +" name:"+stemp[j].getName()+" Age:"+stemp[j].getAge() );
}
reader.close(); // VERY IMPORTANT TO CLOSE
System.out.println("Now writing the file to Xanadu.txt ");
PrintWriter out = new PrintWriter(
new FileWriter("file_name"));
for (int i = 0; i < 3; i++)
{
out.println("Value at: "+ i + " = "+ stemp[i].getName());
}
System.out.println("Successfully wrote to file");
out.close();
}
catch(java.io.IOException ex)
{
System.out.println("Error is " + ex.getMessage() );
}
}
}
該程序執行成功,但是當我打開輸出文件Xanadu.txt時,什么也沒看到。 有人可以指導我嗎? Xanadu.txt文件的內容是對象stemp的數組,該對象具有兩個屬性name和age。
最好的方法就是使其簡單:嘗試下面的代碼:
fos=new File(filepath);
if(fos.exists() && fos.isFile() && !fos.isDirectory())
{
FileWriter fw=new FileWriter(fos);
BufferedWriter Bw= new BufferedWriter(fw);
Bw.append("i am appending text to the existing file");
}
如果要通過創建新文件進行寫入,請先進行文件搜索,如果不存在,請使用以下方法在相同的位置創建和寫入數據:
fos=new File(filepath);
if(!fos.exists() && !fos.isFile())
{
FileWriter fw=new FileWriter(fos);
BufferedWriter Bw= new BufferedWriter(fw);
Bw.write("i am writing text to the existing file");
}
file_name
周圍不能帶引號。 如果將它們放在一起,它將被解釋為字符串,並且數據將被寫入工作目錄中名為“ file_name”的文件中。
PrintWriter out = new PrintWriter(
new FileWriter(file_name));
...會是正確的
PrintWriter out = new PrintWriter(new FileWriter("file_name"));
您傳遞的字符串說:“ file_name”,嘗試這樣做:
PrintWriter out = new PrintWriter(new FileWriter(new File(file_name)));
我認為應該可以。 我認為,由於FileWriter構造函數應將File作為參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.