![](/img/trans.png)
[英]how do i convert my json response to a txt tab delimited file rest api java?
[英]How do I convert my txt file to a String
如何將txt文件轉換為在newGame
方法中讀取的String
? 我需要使用給定的界面。 使用的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();
}
}
}
}
嘗試-
String output = new Scanner(new File("file.txt")).useDelimiter("\\Z").next();
您可以使用帶有嵌套for循環的逗號/換行分隔的Scanner
,通過接口與數據進行匹配:
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());
}
}
塞特犬看起來像這樣:
public void setValueAt(int r, int c, int v) throws InputOutOfRangeException, ValueNotValidException {
// Handle InputOutOfRangeException, ValueNotValidException
boardValues[r][c] = v;
}
只需使用BufferedReaders readline()方法讀取每一行。 然后逐行查找該行中的整數,並將其繼續添加到2d數組中。
看看org.apache.commons.io.IOUtils.readFully()
和org.apache.commons.io.IOUtils.readLines
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.