2

如何将我的 txt 文件转换为String我在方法中读取的文件newGame?我需要使用我给定的界面。使用的 txt 文件是一个 9x9 矩阵。然后我需要将其转换为 2D 数组,我该如何将 String 文件也转换为 2D int 文件。

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.Scanner;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;


public class GameManager implements SudokuBoardManager
{

private static GameManager myBoard;

public static void main(String[] args)
{
    myBoard = new GameManager();
    JFileChooser chooser = new JFileChooser();
    myBoard.newGame(chooser.getSelectedFile());
    System.out.println(myBoard.toString());


}

@Override
public void setValueAt(int r, int c, int v) throws InputOutOfRangeException, ValueNotValidException 
{


}

@Override
public int getValueAt(int r, int c) throws InputOutOfRangeException 
{
    return 0;
}

@Override
public int[] displayPossibleValues(int r, int c)throws InputOutOfRangeException 
{
    return null;
}

public String toString()
{

    return " ";
}

@Override
public void newGame(File gameFile) 
{
    JFileChooser chooser = new JFileChooser();
    int status;
    Scanner in = null;

    chooser.setDialogTitle("Select Sudoku Game File");
    status = chooser.showOpenDialog(null);
    if(status == JFileChooser.APPROVE_OPTION)
    {
        try
        {
            gameFile = chooser.getSelectedFile();
            in = new Scanner(gameFile); 
        }
        catch(InputMismatchException e)
        {
            e.printStackTrace();
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}




}
4

4 回答 4

3

尝试 -

String output = new Scanner(new File("file.txt")).useDelimiter("\\Z").next();
于 2012-09-14T19:24:43.160 回答
1

Scanner您可以使用以嵌套 for 循环分隔的逗号/换行符将数据与接口匹配:

Scanner scanner = new Scanner(new File("game.txt")).useDelimiter(",|\r\n");
for (int i=0; i < 9; i++) {
   for (int j=0; j < 9; j++) {
      myBoard.setValueAt(i, j, scanner.nextInt());
   }
}

Setter 看起来像这样:

public void setValueAt(int r, int c, int v) throws InputOutOfRangeException, ValueNotValidException {
    // Handle InputOutOfRangeException, ValueNotValidException
    boardValues[r][c] = v;
}
于 2012-09-14T20:02:19.133 回答
0

只需使用 BufferedReaders readline() 方法读取每一行。然后一一找到该行中的整数并继续将它们添加到您的二维数组中。

于 2012-09-14T19:17:53.287 回答
0

看看org.apache.commons.io.IOUtils.readFully()org.apache.commons.io.IOUtils.readLines

网址是http://commons.apache.org/io/

于 2012-09-14T19:32:16.577 回答