java 文件偏移,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.

Enter The Sentence:

heey

Enter location:

5

String index out of range: 9

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());

}

}

}

解决方案

The line

bufferedWriter.write(sentence, offset, len);

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

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.

Also you should not be using

@SuppressWarnings("resource")

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值