How to I convert my txt file to a String
that I read in my newGame
method? I need to use my given interface. The txt file used is a 9x9 matrix. Then I need to convert that into a 2D array, how may I go about converting the String file in to a 2D int file as well.
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();
}
}
}
}
尝试-
String output = new Scanner(new File("file.txt")).useDelimiter("\\Z").next();
You could match with your data with the interface using a comma/newline delimited Scanner
with nested for loop:
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 would look like this:
public void setValueAt(int r, int c, int v) throws InputOutOfRangeException, ValueNotValidException {
// Handle InputOutOfRangeException, ValueNotValidException
boardValues[r][c] = v;
}
Just read each line using BufferedReaders readline() method. Then find the integers in that line one by one & keep adding them in your 2d array.
Have a look at org.apache.commons.io.IOUtils.readFully()
and org.apache.commons.io.IOUtils.readLines
.
The url is http://commons.apache.org/io/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.