如何将带有 writeObject() 的 txt 导出到字符串中的路径?

How can I export txt with writeObject() to a path within a string?

我一直在尝试使用 writeObject 方法导出,但如果我在调用 ObjectOutputStream() 方法时直接在输出中直接写入我想要的文件的名称(或路径),我只能导出一个 txt。 我想要的是调用一个我创建的方法,该方法询问用户他想要的文件的名称,然后我将它与路径的其余部分连接起来,如果它应该位于但它不起作用。

这是我想要使用的:

ObjectOutputStream fpsalida = new ObjectOutputStream(new FileOutputStream(nombreArchivo()));

相反,这是让它工作的唯一方法:

ObjectOutputStream fpsalida = new ObjectOutputStream(new FileOutputStream("NameOfTheFileOrCompletePath.txt"));

但是我执行的时候总是收到catch块的消息:

当我执行程序并尝试导出数据时,我收到了捕获块的消息:

/*nombreArchivo is the String with the String returned by nombreArchivo.

将与编写 FileOutputStream(nombreArchivo())) 相同; */ 尝试 { ObjectOutputStream fpsalida = new ObjectOutputStream(new FileOutputStream(nombreArchivo)); //SERIA EL ARG NOMBREARCHIVO

            fpsalida.writeObject(listaprod); //Hay que pasarle el return de la lista de prod.CREAR LA FUNC RETORNAPROD
            System.out.println("\nExportado!\n");

        }catch (IOException e){
            System.out.println("No se ha podido exportar!\n");
        }

    return;
}

这里是我们感兴趣的 nombreArchivo 方法部分:

System.out.println("\nWrite the name of the file you want: ");
    archivoSalida += sc.nextLine() + ".txt";
    System.out.println("==============================================\n");

    //archivoSalida is defined as a String
    return archivoSalida;

}

谢谢。

因为当您 hard-code 文件名时您没有得到 IOException,您的问题是 nombreArchivo() 返回的字符串的实际内容。

要调试问题的具体性质,将返回的字符串分配给一个变量,然后将其记录下来,或者在 System.err 上打印出来,这样您就可以看到它到底是什么:

String fileName = nombreArchivo();
System.err.println("str = \"" + str + \"");
ObjectOutputStream fpsalida = new ObjectOutputStream(new FileOutputStream(fileName));

当您查看错误流时,问题可能会很明显。您还应该考虑在 catch 块中记录或打印出异常的堆栈跟踪:

}catch (IOException e){
    e.printStackTrace();
    System.out.println("No se ha podido exportar!\n");
}

我怀疑 fileName 为 null,空字符串 (""),或者违反 OS 的文件名限制(例如)包含非法字符,例如换行符。

更新: 根据您在下面的评论,问题可能出在 FileOutputStream 计算文件路径的方式上。试试这个,确保从 nombreArchivo() 返回的字符串只是文件名,没有目录路径:

String fileName = nombreArchivo();
String filePath = "file://" + System.getProperty("user.home"); //* You may need to verify that file:// isn't already included in the user's home directory
URL url = new URL(filePath);
File directory = new File(url.toURI());
ObjectOutputStream fpsalida = new ObjectOutputStream(new 
FileOutputStream(new File(directory, fileName)));

说明:我从苦学中学到了这一招。文件路径的计算方式有些微妙,这是我想出的一种使其以 platform-independent 方式工作的方法。

函数 nombreArchivo 似乎确实返回了错误的路径,因为您正在对路径进行硬编码。我认为您的硬编码路径也不正确,但需要查看确切的错误消息才能判断。

我确实测试了 ObjectOutputStream 的这个例子,似乎工作正常。

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;


public class SandBox {

    // get absolute path from relative
    public static String getPath(String relativePath){
        return "/home/mack" + relativePath;
    }

    public static void main(String [] args){
        System.out.println("Write the name of the file you want: ");
        //extract filename from user
        String filename = new Scanner(System.in).nextLine() + ".txt";
        try {
            ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(SandBox.getPath("/" + filename)));
            //write integer to stream
            stream.writeInt(12345);
            stream.close();
        } catch (IOException ex) {
            Logger.getLogger(SandBox.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

问题的原因是文件夹没有创建before.I认为如果目录不存在,它会创建它的方法。