我已编写此代码用于从类路径中读取文件,现在我想在类路径内的同一文件中编写。请告诉我该怎么做?
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.swing.JOptionPane;
public class A {
public A() throws Exception {
final InputStream inputStream = A.class.getResourceAsStream("f/file.txt");
final InputStreamReader r = new InputStreamReader(inputStream);
int end;
String out="";
while((end=r.read())!=-1)
out+=(char)end;
JOptionPane.showMessageDialog(null, out);
}
public static void main(String arg[] ) throws Exception {
new A();
}
}
答案 0 :(得分:1)
如果您尝试写入的文件位于JAR中,则无法正常工作,但通常情况下,您可以检索资源的URL,然后使用该URL写入。
URL url = A.class.getResource("f/file.txt");
File f = new File(url.toURI().getPath());
// binary data
FileOutputStream fos = new FileOutputStream(f);
fos.write( /* data */ );
fos.close();
// OR text
FileWriter fw = new FileWriter(f.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write( /* data */ );
bw.close();
但请记住要小心,文件实际上可以写入。
答案 1 :(得分:0)
如果要记录玩家分数,则必须将其保存在文件中(每个示例中为highscores.dat)。在我查看内容的方式中,您无法在.jar文件中记录,因为de系统正在使用它。
对于记录,您可以创建一个包含一个游戏的高分的类,然后创建一个包含全部高分的数组。
class HighScoreRecord implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private final String name;
private final int highScore;
HighScoreRecord( String name, int highScore ){
this.name = name;
this.highScore = highScore;
}
}
别忘了实现java.io.Serializable,否则你将无法保存它。并且不要忘记创建一个长类型的私有静态字段" serialVersionUID"因为如果没有JVM,它可以归属自己的序列,并且它可能导致与已经记录的文件不兼容。
HighScoreRecord[] highscores = new HighScoreRecord[]{
new HighScoreRecord( "Player1", 1000 ),
new HighScoreRecord( "Player2", 800 ),
new HighScoreRecord( "Player3", 600 ),
new HighScoreRecord( "Player4", 400 ),
new HighScoreRecord( "Player5", 200 )
};
保存记录:
private void writeHighScores() {
FileOutputStream fileOutput = null;
ObjectOutputStream save = null;
try {
//HIGH_SCORES_FILE is any object of type File
fileOutput = new FileOutputStream( HIGH_SCORES_FILE );
save = new ObjectOutputStream( fileOutput );
save.writeObject( highscores );
}
catch ( FileNotFoundException ex ) {
//Exception handling
}
catch ( IOException ex ) {
//Exception handling
}
finally {
if( save != null )
try{
save.close();
} catch ( IOException ex ) {
//Exception handling
}
if( fileOutput != null )
try{
fileOutput.close();
} catch ( IOException ex ) {
//Exception handling
}
}
}
修改强>
加载:
HighScoreRecord[] high = null;
FileInputStream fileInput = null;
ObjectInputStream load = null;
try {
fileInput = new FileInputStream( HIGH_SCORES_FILE );
load = new ObjectInputStream( fileInput );
high = (HighScoreRecord[]) load.readObject();
}
catch ( FileNotFoundException ex ) {
//Exception handling
}
catch ( IOException | ClassNotFoundException ex ) {
//Exception handling
}
finally {
if( load != null )
try{
load.close();
} catch ( IOException ex ) {
//Exception handling
}
if( fileInput != null )
try{
fileInput.close();
} catch ( IOException ex ) {
//Exception handling
}
}
highscores = high;
我希望我有所帮助。
答案 2 :(得分:0)
如果您的应用程序类路径指向您可以写入访问权限的目录,那么在该目录中创建文件后,可以将其作为资源加载。
如果你的类路径中没有目录,你可以创建一个指向目录的类加载器。
此外,如果您使用的是Java 7及更高版本,则应该利用the Path API以及the try-with-resources language feature,这样可以使代码更小,更少错误修剪。
以下是一个例子:
public class FileIO {
public static void main(String[] args) throws IOException {
Path tmpDir = Files.createTempDirectory("test");
String string = "My data";
Path file = tmpDir.resolve("myfile.txt");
System.out.println("File created: " + file);
Files.write(file, string.getBytes());
String myString = new String(Files.readAllBytes(file));
System.out.println("Read from file: " + myString);
URLClassLoader classLoader = new URLClassLoader(new URL[]{tmpDir.toUri().toURL()});
try (InputStream stream = classLoader.getResourceAsStream("myfile.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {
System.out.println("Read from class loader: " + reader.readLine());
}
}
}
输出:
File created: /var/folders/97/63hj35sn6wb0tmcnkrhf5b040000gn/T/test3343347264203608746/myfile.txt
Read from file: My data
Read from class loader: My data