在 Java 中更改 Input.txt 文件中的字符串而不创建 Output.txt

Change String in the Input.txt File in Java without creating Output.txt

如何在不创建新文本的情况下更改文件中的文本?

我正在为我们的项目创建一个吃豆人游戏。 我创建了包含地图和当前进度的 Map.txt 文件。

当玩家踩到字母 f = fruits 时,它会变成 g = grass。

PrintWriter mywriter = new PrintWriter("thisismytextfile.txt", "UTF-8");
mywriter.println("I'm writing to txt-file");
mywriter.close();

这将生成一个 txt 文件并覆盖该文件(如果它已经存在)。

下次先提供你的一些代码。

在游戏初始化时从文件中读取地图。一旦地图加载到内存中,您就可以根据游戏逻辑更改值。您的文件 map.txt 不需要更改。

如果你想用当前的内存值保存你的游戏,你也可以这样做。

这是一个二维字符串数组的示例,用于保存您的地图信息,我将向您展示如何在玩家在迷宫中移动时更改地图:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

public class PacMan extends JFrame {
    private static final long serialVersionUID = 1L;

    protected static final int NUM_ROWS = 14;
    protected static final int NUM_COLUMNS = 14;
    protected static String MAP[][];

    protected static JLabel status = new JLabel("Points: 0");

    public PacMan() {
        super("Pac Man");

        initializeMap();

        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        getContentPane().add(new GamePanel(), BorderLayout.CENTER);
        getContentPane().add(status, BorderLayout.NORTH);

        pack();
        setResizable(false);
        setLocationRelativeTo(null);
    }

    private void initializeMap() {
        int row = 0;
        MAP = new String[NUM_ROWS][NUM_COLUMNS];

        BufferedReader reader = null; 
        try {
            reader = new BufferedReader(new FileReader(new File("map.txt")));
            String line;
            while ((line = reader.readLine()) != null) {
                String[] columns = line.split(" ");
                if(columns.length == NUM_COLUMNS) {
                    for(int column = 0; column < columns.length; column++) {
                        MAP[row][column] = columns[column];
                    }
                }
                row++;
            }
        } 
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if(reader != null) {
                try {
                    reader.close();
                } 
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new PacMan();
                frame.setVisible(true);
            }
        });     
    }
}

class GamePanel extends JPanel implements KeyListener {
    private static final long serialVersionUID = 1L;

    private BufferedImage grass;
    private BufferedImage wall;
    private BufferedImage apple;
    private BufferedImage man;

    private int points = 0;
    private int currentPlayerRow = 1;
    private int currentPlayerCol = 1;

    public GamePanel() {
        try {
            addKeyListener(this);
            setFocusable(true);
            setFocusTraversalKeysEnabled(false);

            grass = ImageIO.read(new File("grass.png"));
            wall = ImageIO.read(new File("wall.png"));
            apple = ImageIO.read(new File("apple.png"));
            man = ImageIO.read(new File("man.png"));
        } 
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        // first, draw all grass in the screen to take advantage
        // of transparent images...
        for(int r = 0; r < PacMan.NUM_ROWS; r++) {
            for(int c = 0; c < PacMan.NUM_COLUMNS; c++) {
                g.drawImage(grass, c * 32, r * 32, null);
            }
        }

        // now just draw all objects (except grass) currently in map. you can 
        // change objects in the map array depending on your game logic elsewhere
        for(int r = 0; r < PacMan.NUM_ROWS; r++) {
            for(int c = 0; c < PacMan.NUM_COLUMNS; c++) {
                if(!PacMan.MAP[r][c].equals("0")) {
                    g.drawImage(getImage(PacMan.MAP[r][c]), c * 32, r * 32, null);
                }
            }
        }       
    }

    private Image getImage(String string) {

        if(string.equals("0")){
            return grass;
        }
        else if(string.equals("a")){
            return apple;
        }
        else if(string.equals("m")){
            return man;
        }       
        else {
            if(string.equals("1")){
                return wall;
            }
        }
        return null;
    }

    public Dimension getPreferredSize() {
        return new Dimension(PacMan.NUM_COLUMNS * 32, PacMan.NUM_ROWS * 32);
    }

    public void keyTyped(KeyEvent e) {}
    public void keyReleased(KeyEvent e) {}  
    public void keyPressed(KeyEvent e) {
        int code = e.getKeyCode();

        if(code == KeyEvent.VK_LEFT && !PacMan.MAP[currentPlayerRow][currentPlayerCol - 1].equals("1")) {
            PacMan.MAP[currentPlayerRow][currentPlayerCol] = "0";
            --currentPlayerCol;
        }
        else if(code == KeyEvent.VK_RIGHT && !PacMan.MAP[currentPlayerRow][currentPlayerCol + 1].equals("1")) {
            PacMan.MAP[currentPlayerRow][currentPlayerCol] = "0";
            ++currentPlayerCol;
        }
        else if(code == KeyEvent.VK_UP && !PacMan.MAP[currentPlayerRow - 1][currentPlayerCol].equals("1")) {
            PacMan.MAP[currentPlayerRow][currentPlayerCol] = "0";
            --currentPlayerRow;
        }
        else {
            if(code == KeyEvent.VK_DOWN && !PacMan.MAP[currentPlayerRow + 1][currentPlayerCol].equals("1")) {
                PacMan.MAP[currentPlayerRow][currentPlayerCol] = "0";
                ++currentPlayerRow;
            }
        }

        if(PacMan.MAP[currentPlayerRow][currentPlayerCol].equals("a")){
            points += 10;
            PacMan.status.setText("Points: " + points);
        }

        PacMan.MAP[currentPlayerRow][currentPlayerCol] = "m";
        repaint();
    }
}

这里是 map.txt 将您的 14x14 磁贴信息存储为文本:

1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 m 0 0 0 1 0 0 0 0 0 0 0 1
1 1 1 1 0 1 0 1 0 0 a 0 0 1
1 0 0 0 0 1 a 1 0 0 0 0 0 1
1 0 1 1 0 0 0 1 1 1 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 a 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 a 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1

最后,使用我自己的 32 像素图块的屏幕截图(不过,您可以使用自己的 32x32 像素图块...

//Main class
package Maze; 

import javax.swing.*;

public class Maze{
    public static void main(String[] args){
        new Maze();
    }

    public Maze(){  //setup the frame of the maze
        JFrame f = new JFrame();   //create the frame
        f.setTitle("Maze Game");   //title of the frame
        f.add(new Board());
        f.setSize(464, 485);       //(width,height) the size of the screen
        f.setLocationRelativeTo(null);  //place the position of the screen in the middle
        f.setVisible(true);        // so that we can see the screen
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   //to close the window
    }
}