0

Javaを使用して新しいデータでファイルを更新しようとしています。次のデータを保存したtxtファイルがあるとします。

id     grade
3498   8
2345   9
5444   7
2222   5

そのため、ユーザーが入力したIDに応じてグレードを更新しようとしていますが、新しい(更新された)ファイルのタイプは次のとおりです。

id   grade3498   62345   95444   72222   5

等々....

これが機能しない理由がわかりません。データの再書き込み中に改行を追加しないことと関係があると思いますが、outobj.writeに改行文字( "\ n")を追加しても(fileContent.toString()); 何も変わりません。

これが私のコードの抜粋です:

public String check(int num) throws RemoteException
{
    String textinLine;
    String texttoEdit;
    File file=new File ("c:\\students.txt");
    FileInputStream stream = null;
    DataInputStream in =null;
    BufferedReader br = null;
    try
        {
        stream = new FileInputStream(file);
        in =new DataInputStream(stream);
        br = new BufferedReader(new InputStreamReader(in));
        StringBuilder fileContent = new StringBuilder();
        if ((num>0) && (num<6001))
            {
            while ((textinLine=br.readLine())!=null)
                {
                texttoEdit=Integer.toString(num);
                    System.out.println(textinLine);
                    String[] parts = textinLine.split(" ");
                    if (parts.length>0)
                        {
                        if (parts[0].equals(texttoEdit))
                            {
                            int value =       Integer.parseInt(parts[1]);
                            value-=2;
                            String edit=Integer.toString(value);
                            String newLine = "\n"+parts[0]+"    "+edit+"\n";
                            msg="You can pass2";
                            fileContent.append(newLine);
fileContent.append("\n");               }
                        else
                            {
                            fileContent.append(textinLine);
fileContent.append("\n");
                            }
                        }
                }
            }
        in.close();
        FileWriter fstream = new FileWriter(file);
        BufferedWriter outobj = new BufferedWriter(fstream);
        outobj.write(fileContent.toString());
        outobj.close();
        }
    catch (FileNotFoundException e)
        {
        e.printStackTrace();
        }
    catch (IOException e)
        {
        e.printStackTrace();
        }

最後に、新しいファイルが正しく編集されているとしましょう。つまり、ユーザーがID 3498を入力すると、グレード値は8-2 = 6に変更されますが、説明したように、新しいファイルは1行になります。前。

4

1 に答える 1

6

\r\n一部のOS(通常はWindows)では、改行に使用する必要があります。さらに良いことに、次を使用できます。

String newLine = System.getProperty("line.separator");

それが実行されているプラ​​ットフォームに応じて調整されるラインセパレーター用。

于 2012-12-03T10:16:56.593 に答える