无法写入文件扫描仪 try/catch Java
Unable to write to file Scanner try/catch Java
当我运行这个程序是要写入文本文件时,文本文件与我的项目文件夹位于同一目录中。
try
{
Scanner inFile = new Scanner(new File ("details.txt"));
while(inFile.hasNext())
{
String line = inFile.nextLine(); //reads the line of text
Scanner del = new Scanner(line).useDelimiter("#"); //scanner class to delimit
String name = del.next();
String gender = del.next();
int age = del.nextInt();
double amount = del.nextDouble();
txaDisplay.append(name+"\t"+gender+"\t"+age+"\t"+amount+"\n");
del.close();
}
inFile.close();//end try
}
catch(FileNotFoundException f)
{
txaDisplay.append("File Not Found");
System.exit(0);}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new yest().setVisible(true);
}
});}
您需要实际写入文件。这是我给不熟悉文件输出的人的一个例子。这使用 FileWriter
输出流。注意 Data
这里是一个 ArrayList
.
public static void WriteFile(File file)
{
System.out.println("Writing to file");
//Use a FileWriter to output to file
FileWriter oFile = null;
try
{
oFile = new FileWriter(file, false); //Set to true if you don't want to overwrite existing contents in file
// Begin writing to file... line by line
for (String line : Data)
oFile.write(line + System.getProperty("line.separator")); //Since notepad doesn't display newline characters (\n) use this
//If using another text document viewer then just use + "\n"
//Flush and close output stream
oFile.flush();
oFile.close();
} catch (IOException e)
{
// Handle it!
e.printStackTrace();
}
}
当我运行这个程序是要写入文本文件时,文本文件与我的项目文件夹位于同一目录中。
try
{
Scanner inFile = new Scanner(new File ("details.txt"));
while(inFile.hasNext())
{
String line = inFile.nextLine(); //reads the line of text
Scanner del = new Scanner(line).useDelimiter("#"); //scanner class to delimit
String name = del.next();
String gender = del.next();
int age = del.nextInt();
double amount = del.nextDouble();
txaDisplay.append(name+"\t"+gender+"\t"+age+"\t"+amount+"\n");
del.close();
}
inFile.close();//end try
}
catch(FileNotFoundException f)
{
txaDisplay.append("File Not Found");
System.exit(0);}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new yest().setVisible(true);
}
});}
您需要实际写入文件。这是我给不熟悉文件输出的人的一个例子。这使用 FileWriter
输出流。注意 Data
这里是一个 ArrayList
.
public static void WriteFile(File file)
{
System.out.println("Writing to file");
//Use a FileWriter to output to file
FileWriter oFile = null;
try
{
oFile = new FileWriter(file, false); //Set to true if you don't want to overwrite existing contents in file
// Begin writing to file... line by line
for (String line : Data)
oFile.write(line + System.getProperty("line.separator")); //Since notepad doesn't display newline characters (\n) use this
//If using another text document viewer then just use + "\n"
//Flush and close output stream
oFile.flush();
oFile.close();
} catch (IOException e)
{
// Handle it!
e.printStackTrace();
}
}