Задался вот вопросом на свою голову, а возможно ли чтение не всего файла, а только его конкретной части. Как и запись. И вообще читает ли File и Fileoutputstream весь файл? И что будет если файл ну чрезмерно большой и хранить его в буфере или копировать весь файл ну совсем не комильфо...
Так вышел на клас RandomAccessFile.🤪
Кто-то решил через него? Обидно будет переписывать полудневный труд...
package com.javarush.task.task18.task1828;
/*
Прайсы
*/
import java.io.*;
public class Solution
{
public static void main(String[] args) throws IOException
{
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
String fileName = console.readLine();
console.close();
//args = new String[]{"-c", "Trusiki shelkovie ochen krutoy poshiv devochki ne pozhaleyete", "200.00", "21"};
//args = new String[]{"-c", "Truhaleti batini ogromnie vonuchie extra v serdechko", "10.00", "1"};
//args = new String[]{"-c", "kepka", "100.00", "150"};
//updateData("E:\\Tovari.txt", "20000002", new String[]{"-u", "20000002", "Validator padlo", "10000.00", "1"});
if (args.length <= 0)
{
return;
}
String comand = args[0];
switch (comand)
{
/*case ("-c"):
int maxID = getMaxID(fileName);
writeData(fileName, maxID, args);
break;*/
case ("-u"):
updateData(fileName, args[1], args);
break;
case ("-d"):
deleteData(fileName, args[1]);
break;
/*default:
System.out.println("Check args");
break;*/
}
}
private static int getStringNumber(String fileName, String stringID)
{
String searchID = formatString(stringID, 8, " ");
int lineNumber = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(fileName)))
{
String line;
while ((line = reader.readLine()) != null)
{
lineNumber++;
String id = line.substring(0, 8);
if (id.equals(searchID))
{
break;
}
}
return lineNumber;
}
catch (FileNotFoundException e)
{
return lineNumber;
}
catch (IOException e)
{
return lineNumber;
}
}
private static void updateData(String fileName, String stringID, String[] args)
{
try (RandomAccessFile file = new RandomAccessFile(fileName, "rw"))
{
int stringNumber = getStringNumber(fileName, stringID);
int Pos = file.skipBytes((stringNumber - 1) * 52);
file.seek(Pos);
StringBuilder sb = new StringBuilder();
sb.append(formatString(stringID, 8, " "));
String productName = formatString(args[2], 30, " ");
sb.append(productName);
String price = formatString(args[3], 8, " ");
sb.append(price);
String quantity = formatString(args[4], 4, " ");
sb.append(quantity);
String newString = sb.toString();
file.write(newString.getBytes());
}
catch (FileNotFoundException e)
{
System.out.println("No such file");
}
catch (IOException e)
{
System.out.println("Error during reading");
}
}
private static void deleteData(String fileName, String stringID)
{
int stringNumber = getStringNumber(fileName, stringID);
try (RandomAccessFile file = new RandomAccessFile(fileName, "rw"))
{
int writePos = file.skipBytes((stringNumber - 1) * 52);
int readPos = file.skipBytes(stringNumber * 52);
file.seek(readPos);
String temp;
while ((temp = file.readLine()) != null)
{
file.seek(writePos);
file.write((temp + System.lineSeparator()).getBytes());
writePos += 52;
readPos += 52;
file.seek(readPos);
}
file.setLength(file.length() - 52);
}
catch (FileNotFoundException e)
{
System.out.println("No such file");
}
catch (IOException e)
{
System.out.println("Error during reading");
}
}
/*private static int getMaxID(String fileName)
{
try (BufferedReader reader = new BufferedReader(new FileReader(fileName)))
{
int max = Integer.MIN_VALUE;
String line;
while ((line = reader.readLine()) != null)
{
String stringID = line.substring(0, 8);
//System.out.println(stringID.indexOf(" "));
int lastIndex = (!stringID.contains(" ")) ? stringID.length() : stringID.indexOf(" ");
int id = Integer.parseInt(stringID.substring(0, lastIndex));
if (id > max)
{
max = id;
}
}
return max;
}
catch (FileNotFoundException e)
{
//System.out.println("No such file");
return 0;
}
catch (IOException e)
{
//System.out.println("Error during reading");
return 0;
}
}
private static void writeData(String fileName, int maxID, String[] args)
{
try (BufferedOutputStream bfos = new BufferedOutputStream(new FileOutputStream(fileName, true)))
{
StringBuilder sb = new StringBuilder();
sb.append(System.lineSeparator());
String newID = formatString(String.valueOf((maxID + 1)), 8, " ");
sb.append(newID);
String productName = formatString(args[1], 30, " ");
sb.append(productName);
String price = formatString(args[2], 8, " ");
sb.append(price);
String quantity = formatString(args[3], 4, " ");
sb.append(quantity);
String newString = sb.toString();
bfos.write(newString.getBytes());
}
catch (FileNotFoundException e)
{
System.out.println("No such file");
}
catch (IOException e)
{
System.out.println("Error during reading");
}
}*/
private static String formatString(String inputString, int lenght, String filler)
{
if (inputString.length() >= lenght)
{
return inputString.substring(0, lenght);
}
else
{
StringBuilder sb = new StringBuilder();
sb.append(inputString);
while (sb.length() < lenght)
{
sb.append(filler);
}
return sb.toString();
}
}
}