首页 \ 问答 \ 在Java中读取(分配)txt.file值(Reading (assigning) txt.file values in Java)

在Java中读取(分配)txt.file值(Reading (assigning) txt.file values in Java)

更新:我使用'\ n'来区分saveGame方法中的每一行,该方法在API中指定。 这意味着readLine应正确查找文件中的每一行,分配其值并在读取最后一行后关闭。 但是,我仍然得到“null”(NullPointerException)作为输出...

这是在API中指定null的方式:

(readLine)返回:

包含行内容的String,不包括任何行终止字符;如果已到达流的末尾,则为null


我正在尝试读取txt文件并将其行分配到int [] []数组中。

这是我的savegame.txt文件的示例:

0 

0

-1

0

1

-1

1

0

0

每一行代表一个int值。 我的saveGame方法将数组“gameBoard”的当前int值写入上面显示的文件中。 此示例表示以下游戏状态:

  |   | O 

  | X | O

X |   |  

但是,当我尝试使用我的loadGame方法读取savegame.txt文件时,该方法将每个gameBoard-position [0] [0]分配给[2] [2]各自的值,我得到null作为输出并且游戏开始用一个空数组。 从我的逻辑来看,我的loadGame方法应该单独读取每一行并将其String-value解析为一个Integer,而我的int [] []数组gameBoard可以解释它。 我想知道为什么这不能正常工作。

FileManagement.class

package storagePack;

import structurePack.Board;

import java.io.*;
import java.util.Scanner;

/**
 * The FileManagement-Class is responsible for the saving and loading of gamedata.
 * It saves the current gameBoard and reads it with the loadGame Method.
 */

public class FileManagement {
    static String filename = "Savegame.txt";

/**
 * Schema:
 * (0,0) | (0,1) | (0,2)
 * (1,0) | (1,1) | (1,2)
 * (2,0) | (2,1) | (2,2)
 */
/**
 * @param gameBoard, the currently active Array from the Board.class.
 * @throws Exception, FileNotFoundException
 */
public static void saveGame(int[][] gameBoard) throws Exception {
    //serialization
    PrintWriter writer;
    try {

        writer = new PrintWriter(new FileOutputStream(filename), false);
        for (int i = 0; i < gameBoard.length; i++) {
            for (int j = 0; j < gameBoard.length; j++) {
                int entry = gameBoard[i][j];
                writer.print(entry);
                writer.println('\n');
            }

        }
        writer.close();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

/**
 * @throws Exception, FileNotFoundException
 */
public static void loadGame() throws Exception {
    //deserialization
    FileReader fileReader = new FileReader(filename);
    BufferedReader bufferedReader = new BufferedReader (fileReader);
    try {
        structurePack.Board.gameBoard[0][0] = Integer.parseInt(bufferedReader.readLine());
        structurePack.Board.gameBoard[0][1] = Integer.parseInt(bufferedReader.readLine());
        structurePack.Board.gameBoard[0][2] = Integer.parseInt(bufferedReader.readLine());
        structurePack.Board.gameBoard[1][0] = Integer.parseInt(bufferedReader.readLine());
        structurePack.Board.gameBoard[1][1] = Integer.parseInt(bufferedReader.readLine());
        structurePack.Board.gameBoard[1][2] = Integer.parseInt(bufferedReader.readLine());
        structurePack.Board.gameBoard[2][0] = Integer.parseInt(bufferedReader.readLine());
        structurePack.Board.gameBoard[2][1] = Integer.parseInt(bufferedReader.readLine());
        structurePack.Board.gameBoard[2][2] = Integer.parseInt(bufferedReader.readLine());
        fileReader.close();
        bufferedReader.close();

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}
}

readLine API-文档

public String readLine()
                throws IOException

Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

Throws:
IOException - If an I/O error occurs

See Also:
Files.readAllLines(java.nio.file.Path, java.nio.charset.Charset)

Update: I'm using '\n' to diverse each line in the saveGame method, which is specified in the API. This means readLine should correctly find each individual line in the file, assign its value and close after it has read the last line. However, I still get "null" (NullPointerException) as output...

This is how null is specified in the API:

(readLine) Returns:

A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached


I'm trying to read a txt file and assign its lines into an int [][] array.

This is an example on how my savegame.txt file looks like:

0 

0

-1

0

1

-1

1

0

0

Every line represents a int-value. My saveGame method writes the current int-values of the array "gameBoard" into the above shown file. This example represents the following game state:

  |   | O 

  | X | O

X |   |  

However, when I try to read the savegame.txt file with my loadGame method, which assigns each individual gameBoard-position [0][0] to [2][2] its respective values, I get null as output and the game starts with an empty array. From my logic, my loadGame method should read every line seperately and parse its String-value into an Integer which than can be interpreted by my int[][] array gameBoard. I wonder why this does not work correctly.

FileManagement.class

package storagePack;

import structurePack.Board;

import java.io.*;
import java.util.Scanner;

/**
 * The FileManagement-Class is responsible for the saving and loading of gamedata.
 * It saves the current gameBoard and reads it with the loadGame Method.
 */

public class FileManagement {
    static String filename = "Savegame.txt";

/**
 * Schema:
 * (0,0) | (0,1) | (0,2)
 * (1,0) | (1,1) | (1,2)
 * (2,0) | (2,1) | (2,2)
 */
/**
 * @param gameBoard, the currently active Array from the Board.class.
 * @throws Exception, FileNotFoundException
 */
public static void saveGame(int[][] gameBoard) throws Exception {
    //serialization
    PrintWriter writer;
    try {

        writer = new PrintWriter(new FileOutputStream(filename), false);
        for (int i = 0; i < gameBoard.length; i++) {
            for (int j = 0; j < gameBoard.length; j++) {
                int entry = gameBoard[i][j];
                writer.print(entry);
                writer.println('\n');
            }

        }
        writer.close();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

/**
 * @throws Exception, FileNotFoundException
 */
public static void loadGame() throws Exception {
    //deserialization
    FileReader fileReader = new FileReader(filename);
    BufferedReader bufferedReader = new BufferedReader (fileReader);
    try {
        structurePack.Board.gameBoard[0][0] = Integer.parseInt(bufferedReader.readLine());
        structurePack.Board.gameBoard[0][1] = Integer.parseInt(bufferedReader.readLine());
        structurePack.Board.gameBoard[0][2] = Integer.parseInt(bufferedReader.readLine());
        structurePack.Board.gameBoard[1][0] = Integer.parseInt(bufferedReader.readLine());
        structurePack.Board.gameBoard[1][1] = Integer.parseInt(bufferedReader.readLine());
        structurePack.Board.gameBoard[1][2] = Integer.parseInt(bufferedReader.readLine());
        structurePack.Board.gameBoard[2][0] = Integer.parseInt(bufferedReader.readLine());
        structurePack.Board.gameBoard[2][1] = Integer.parseInt(bufferedReader.readLine());
        structurePack.Board.gameBoard[2][2] = Integer.parseInt(bufferedReader.readLine());
        fileReader.close();
        bufferedReader.close();

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}
}

readLine API-Documentation

public String readLine()
                throws IOException

Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

Throws:
IOException - If an I/O error occurs

See Also:
Files.readAllLines(java.nio.file.Path, java.nio.charset.Charset)

原文:https://stackoverflow.com/questions/37322476
更新时间:2022-08-29 12:08

最满意答案

目前还不完全清楚你要求的是什么,但听起来你试图在达到一定条件之前加上延迟,并同时返回触发条件的记录。

您可以像使用Enumerable#detect那样接近它,但是通过保持一个标记:

def next_event_info
  next_event = nil
  delay = 0

  events.detect do |event|
    case (self.event_status(event))
    when "no status"
      true
    else
      delay += contact.event_delay(event)
      false
    end
  end

  [ next_event, delay ]
end

更新如果您想要为所有事件添加所有延迟,还要查找状态为"no status"的第一个事件:

def next_event_info
  next_event = nil
  delay = 0.0

  events.each do |event|
    case (self.event_status(event))
    when "no status"
      # Only assign to next_event if it has not been previously
      # assigned in this method call.
      next_event ||= event
    end

    # Tally up the delays for all events, converting to floating
    # point to ensure they're not native DB number types.
    delay += contact.event_delay(event).to_f
  end

  {
    :event => next_event,
    :delay => delay
  }
end

这将为您提供一个Hash作为回报,您可以询问info[:event]info[:delay] 。 请记住不要滥用此方法,例如:

# Each of these makes a method call, which is somewhat expensive
next_event = next_event_info[:event]
delay_to_event = next_event_info[:delay]

这将对此方法进行两次调用,这两次调用将迭代所有记录并进行计算。 如果你需要以这种方式使用它,你也可以为每个操作创建一个特殊用途的函数,或者将结果缓存到一个变量中并使用它:

# Make the method call once, save the results
event_info = next_event_info

# Use these results as required
next_event = event_info[:event]
delay_to_event = event_info[:delay]

It's not entirely clear what you're asking for, but it sounds like you're trying to add up a delay until you reach a certain condition, and return the record that triggered the condition at the same time.

You might approach that using Enumerable#detect like you have, but by keeping a tally on the side:

def next_event_info
  next_event = nil
  delay = 0

  events.detect do |event|
    case (self.event_status(event))
    when "no status"
      true
    else
      delay += contact.event_delay(event)
      false
    end
  end

  [ next_event, delay ]
end

Update for if you want to add up all delays for all events, but also find the first event with the status of "no status":

def next_event_info
  next_event = nil
  delay = 0.0

  events.each do |event|
    case (self.event_status(event))
    when "no status"
      # Only assign to next_event if it has not been previously
      # assigned in this method call.
      next_event ||= event
    end

    # Tally up the delays for all events, converting to floating
    # point to ensure they're not native DB number types.
    delay += contact.event_delay(event).to_f
  end

  {
    :event => next_event,
    :delay => delay
  }
end

This will give you a Hash in return that you can interrogate as info[:event] or info[:delay]. Keep in mind to not abuse this method, for example:

# Each of these makes a method call, which is somewhat expensive
next_event = next_event_info[:event]
delay_to_event = next_event_info[:delay]

This will make two calls to this method, both of which will iterate over all the records and do the calculations. If you need to use it this way, you might as well make a special purpose function for each operation, or cache the result in a variable and use that:

# Make the method call once, save the results
event_info = next_event_info

# Use these results as required
next_event = event_info[:event]
delay_to_event = event_info[:delay]

相关问答

更多
  • 红宝石filemagic宝石将做到这一点: require 'filemagic' puts FileMagic.new(FileMagic::MAGIC_MIME).file(__FILE__) # => text/x-ruby; charset=us-ascii 这个宝石根本没有看文件扩展名。 它读取一些文件内容并使用它来猜测文件的类型。 The ruby-filemagic gem will do it: require 'filemagic' puts FileMagic.new(FileMa ...
  • 贡献者为此目的添加了新的配置选项track_files 。 对于rails项目,值可能如下所示 track_files '{app,lib}/**/*.rb' 更多细节: https : //github.com/colszowka/simplecov/pull/422 The contributors added new config optiontrack_files exactly for this purpose. For rails project the value could look lik ...
  • 如评论中所述,纯粹为了检测并返回第一个非零映射值,这适用: die "Module refinements need 2.4" if RUBY_VERSION < "2.4.0" module MapDetectFirstRefinement refine Enumerable do def map_detect_first each_with_object(nil) do |e, _| mapped = yield e return mapped ...
  • 这不是Ruby On Rails的构建,这是ERB模板引擎的构建。 如果你喜欢,你可以使用haml或其他模板引擎。 这是相当古老,但有趣的审查其中许多人。 That isn't Ruby On Rails construction, that's construction of ERB template engine. If you like, you can use haml or any other template engine. This is rather old, but interesting ...
  • 我在红宝石中找到了一个技巧,并且确实起了作用。 我使用browser gem来告诉你请求设计是“移动or平板电脑”。 我只是否定了响应并将其视为桌面,如果它不是移动设备而不是平板设备。 有关更多说明,请参阅安装gem后的代码段。 这是参考 需要“浏览器” browser = Browser.new(:ua => request.user_agent,:accept_language =>“en-us”) if!browser.mobile? &&!browser.tablet? @device =“桌面” ...
  • 你需要做的就是用一个对象调用render:json,如下所示: render :json => my_object 对于大多数对象来说,这只会起作用。 如果它是一个ActiveRecord对象,请确保查看as_json以查看它是如何工作的。 对于上面说明的情况,您的散列将被转换为json并返回。 但是,您确实有一个错误:您无法通过response.success访问成功键 - 您应该改为使用response [:success] All you need to do is call render :jso ...
  • 目前还不完全清楚你要求的是什么,但听起来你试图在达到一定条件之前加上延迟,并同时返回触发条件的记录。 您可以像使用Enumerable#detect那样接近它,但是通过保持一个标记: def next_event_info next_event = nil delay = 0 events.detect do |event| case (self.event_status(event)) when "no status" true else de ...
  • which是一个Unix实用程序,它搜索PATH以查找与您提供的参数匹配的可执行文件,并返回该可执行文件的完整路径。 您可以使用路径中包含的任何可执行文件执行此操作,而不仅仅是Ruby或Rails。 另一方面,当你键入ruby -v ,你实际上是用-v作为命令行参数调用Ruby可执行文件,告诉它返回它的版本。 你总是会得到你当前Ruby的版本。 同样适用于Rails。 Ruby和Rails的切换版本取决于您正在使用的管理工具。 对于RVM (Ruby版本管理器), use ruby 2.5.0将当前版本的R ...
  • input, output, error = Open3.popen3 "nikto -host someip -port 80 -output xml" if select([output], nil, nil, 0.1) and output.eof? # process exited and doesn't have output queued. else # still running or has output not read yet. end 此外,这里是我通过谷歌搜索找到的一些很 ...
  • 我见过的最优雅的解决方案是做两件事:在请求中基于用户代理识别移动用户,并使用自定义Rails mime类型进行响应,允许移动用户使用自定义HTML模板。 在config/initializers/mime_types.rb中定义一个自定义的“移动”Rails MIME类型,它只是HTML: Mime::Type.register_alias "text/html", :mobile 添加帮助/过滤器以响应移动用户: def mobile_user_agent? @mobile_user_agent | ...

相关文章

更多

最新问答

更多
  • python的访问器方法有哪些
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。
  • 响应navi重叠h1和nav上的h1链接不起作用(Responsive navi overlaps h1 and navi links on h1 isn't working)
  • 在C中读取文件:“r”和“a +”标志的不同行为(Reading a File in C: different behavior for “r” and “a+” flags)
  • NFC提供什么样的带宽?(What Kind of Bandwidth does NFC Provide?)
  • 元素上的盒子阴影行为(box-shadow behaviour on elements)
  • Laravel检查是否存在记录(Laravel Checking If a Record Exists)
  • 设置base64图像的大小javascript - angularjs(set size of a base64 image javascript - angularjs)
  • 想学Linux 运维 深圳有哪个培训机构好一点
  • 为什么有时不需要在lambda中捕获一个常量变量?(Why is a const variable sometimes not required to be captured in a lambda?)
  • 在Framework 3.5中使用服务器标签<%=%>设置Visible属性(Set Visible property with server tag <%= %> in Framework 3.5)
  • AdoNetAppender中的log4net连接类型无效(log4net connection type invalid in AdoNetAppender)
  • 错误:发送后无法设置标题。(Error: Can't set headers after they are sent. authentication system)
  • 等待EC2实例重启(Wait for an EC2 instance to reboot)
  • 如何在红宝石中使用正则表达式?(How to do this in regex in ruby?)
  • 使用鼠标在OpenGL GLUT中绘制多边形(Draw a polygon in OpenGL GLUT with mouse)
  • 江民杀毒软件的KSysnon.sys模块是什么东西?
  • 处理器在传递到add_xpath()或add_value()时调用了什么顺序?(What order are processors called when passed into add_xpath() or add_value()?)
  • sp_updatestats是否导致SQL Server 2005中无法访问表?(Does sp_updatestats cause tables to be inaccessible in SQL Server 2005?)
  • 如何创建一个可以与持续运行的服务交互的CLI,类似于MySQL的shell?(How to create a CLI that can interact with a continuously running service, similar to MySQL's shell?)
  • AESGCM解密失败的MAC(AESGCM decryption failing with MAC)
  • SQL查询,其中字段不包含$ x(SQL Query Where Field DOES NOT Contain $x)
  • PerSession与PerCall(PerSession vs. PerCall)
  • C#:有两个构造函数的对象:如何限制哪些属性设置在一起?(C#: Object having two constructors: how to limit which properties are set together?)
  • 平衡一个精灵(Balancing a sprite)
  • n2cms Asp.net在“文件”菜单上给出错误(文件管理器)(n2cms Asp.net give error on Files menu (File Manager))
  • Zurb Foundation 4 - 嵌套网格对齐问题(Zurb Foundation 4 - Nested grid alignment issues)
  • 湖北京山哪里有修平板计算机的