无法创建txt文件

时间:2015-11-19 07:56:07

标签: java file-io

import java.util.Scanner;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
public class Exercise4
{
String name = null;
public String nameInitials(String sentence)
{
PrintWriter outputStream = null;
try
{
    outputStream = new PrintWriter(new FileOutputStream("abc.txt."));
    outputStream.println(sentence);
}
catch (FileNotFoundException e)
{
    System.out.println("File not found.");
    System.exit(0);
}
outputStream.close();
Scanner inputStream = null;
try
{
    inputStream = new Scanner(new FileInputStream("abc.txt."));
}
catch (FileNotFoundException e)
{
    System.out.println("File not found.");
    System.exit(0);
}
do
{
    String word = inputStream.next();
    char initial = word.charAt(0);
    name = initial+"."+name;
} while (inputStream.hasNext());
return name;
}
public void main(String[]args)
{
String initials = nameInitials("Bertrand Arthur William Russell");
System.out.println(initials);
}
}

编写一个名为nameInitials的方法,该方法将一个String作为参数,与某人的全名有关,并返回名称首字母的字符串。用法示例,

String initials = nameInitials("Bertrand Arthur William Russell");
System.out.println(initials); //should print B.A.W.R.

我尝试将全名存储到txt文件并读取文件。但我不知道为什么我不能在文件夹中创建abc.txt文件。

2 个答案:

答案 0 :(得分:0)

这可以解决您的错误,我测试了它

 import java.util.Scanner;
 import java.io.FileInputStream;
 import java.io.PrintWriter;
 import java.io.FileOutputStream;
 import java.io.FileNotFoundException;
public class Exercise4
{
    static String name = null;

public static String nameInitials(String sentence) {
    PrintWriter outputStream = null;
    try {
        outputStream = new PrintWriter(new FileOutputStream("C:\\temp\\abc.txt"));
        outputStream.println(sentence);
    } catch (FileNotFoundException e) {
        System.out.println("File not found.");
        System.exit(0);
    }
    outputStream.close();
    Scanner inputStream = null;
    try {
        inputStream = new Scanner(new FileInputStream("C:\\temp\\abc.txt"));
    } catch (FileNotFoundException e) {
        System.out.println("File not found.");
        System.exit(0);
    }
    do {
        String word = inputStream.next();
        char initial = word.charAt(0);
        name = initial + "." + name;
    } while (inputStream.hasNext());
    return name;
}

public static void main(String[] args) {
    String initials = nameInitials("Bertrand Arthur William Russell");
    System.out.println(initials);
}
 }

文件的路径不应该以.txt结尾。只是.txt

答案 1 :(得分:0)

您的代码非常完美,它在项目级别创建文件“abc.txt.”如果您要创建名为abc.txt的文件,则必须更改;

new FileOutputStream("abc.txt.")new FileOutputStream("abc.txt")

new FileInputStream("abc.txt.")new FileInputStream("abc.txt")

如果您想在特定目录中创建文件,请提供该目录的完整路径以及您要创建的文件名。

用于ubuntu系统;

new FileOutputStream("/home/java/abc.txt")

&安培;

new FileInputStream("/home/java/abc.txt")

和Windows系统;

new FileOutputStream("C:/java/abc.txt")

&安培;

new FileInputStream("C:/java/abc.txt")