JAVA写入具有特定偏移量的文件 [英] JAVA Writing to a file with specific offset

查看:613
本文介绍了JAVA写入具有特定偏移量的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须编写一个程序来读取文件并插入用户通过控制台窗口给出的一些文本。插入文本的位置也应该通过控制台窗口给出。

I have to write a program that reads a file and inserts some text given by the user through the console window. The location in which the text is inserted should also be given through the console window.

下面是我的代码,输入后我得到字符串索引超出范围句子和偏移。

Below is my code, I am getting "String index out of range" after entering the sentence and offset.

输入句子:
heey

Enter The Sentence: heey

输入位置:
5

Enter location: 5

字符串索引超出范围:9 < - 这是错误,

String index out of range: 9 <-- this is the error ,

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.FileInputStream; 
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.util.Scanner;
import java.io.Writer;


class ReadPosition{ 
    public static void main(String args[])    {   
    try{       
        FileWriter Writer =
                new FileWriter("in.txt");
        @SuppressWarnings("resource")
        BufferedWriter bufferedWriter =
                new BufferedWriter(Writer);


        Scanner input= new Scanner(System.in);
        System.out.println("Enter The Sentence: ");
        String sentence = input.nextLine();  
        System.out.println("Enter location: ");
        int offset = input.nextInt();
        input.close();

        byte[] buffer = sentence.getBytes();
        int len = buffer.length;
        bufferedWriter.write(sentence, offset, len);

    }

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


    }

}


推荐答案

该行

bufferedWriter.write(sentence, offset, len);

表示从<$写出 len 字符c $ c>句子在句子中以 offset 开头。

means write out len characters from sentence starting at offset in sentence.

换句话说 offset 是句子中中的位置输出文件。

In other words offset is the position in the sentence not the position in the output file.

如果要在文件中插入文本,则需要编写代码将文件复制到新文件,在复制期间将文本添加到正确的位置。

If you want to insert text in a file you need to write code to copy the file to a new file adding the text at the correct position during the copy.

此外你不应该使用

@SuppressWarnings("resource")

来抑制关闭缺失警告 - 你需要关闭你的作者。

to suppress the close missing warning - you do need to close your writer.

这篇关于JAVA写入具有特定偏移量的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆