Вы не можете читать и писать из / в один и тот же файл одновременно. Не с StreamReader
и StreamWriter
, ни с любым другим обычным методом. Если вам необходимо изменить существующий файл и не можете (или не хотите) читать весь его контент в памяти, вы должны записать измененный контент во временный файл, а затем заменить оригинал на временный файл после закрытия обоих файлов.
Пример:
$filename = (Get-Item $file).Name
$streamReader = New-Object IO.StreamReader -Arg $file
$streamWriter = [System.IO.StreamWriter] "$file.tmp"
...
$streamReader.Close(); $streamReader.Dispose()
$streamWriter.Close(); $streamWriter.Dispose()
Remove-Item $file -Force
Rename-Item "$file.tmp" -NewName $filename
Мы используем HttpClient 4.x для публикации составных файлов.
ОБНОВЛЕНИЕ : Начиная с HttpClient 4.3 , некоторые классы устарели. Вот код с новым API:
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost("...");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN);
// This attaches the file to the POST:
File f = new File("[/path/to/upload]");
builder.addBinaryBody(
"file",
new FileInputStream(f),
ContentType.APPLICATION_OCTET_STREAM,
f.getName()
);
HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
CloseableHttpResponse response = httpClient.execute(uploadFile);
HttpEntity responseEntity = response.getEntity();
Ниже приведен исходный фрагмент кода с устаревшим API HttpClient 4.0 :
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
FileBody bin = new FileBody(new File(fileName));
StringBody comment = new StringBody("Filename: " + fileName);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("bin", bin);
reqEntity.addPart("comment", comment);
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
Мое сообщение кода multipartFile к серверу.
public static HttpResponse doPost(
String host,
String path,
String method,
MultipartFile multipartFile
) throws IOException
{
HttpClient httpClient = wrapClient(host);
HttpPost httpPost = new HttpPost(buildUrl(host, path));
if (multipartFile != null) {
HttpEntity httpEntity;
ContentBody contentBody;
contentBody = new ByteArrayBody(multipartFile.getBytes(), multipartFile.getOriginalFilename());
httpEntity = MultipartEntityBuilder.create()
.addPart("nameOfMultipartFile", contentBody)
.build();
httpPost.setEntity(httpEntity);
}
return httpClient.execute(httpPost);
}
http-компоненты-клиент-4.0.1
работали на меня. Однако, мне пришлось добавить внешнюю банку apache-mime4j-0.6.jar
(org.apache.james.mime4j) иначе.
reqEntity.addPart("bin", bin);
не будет компилироваться. Теперь он работает как шарм.
Это зависимости Maven, которые у меня есть.
Код Java:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
FileBody uploadFilePart = new FileBody(uploadFile);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("upload-file", uploadFilePart);
httpPost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httpPost);
Зависимости Maven в pom.xml:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.0.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.0.1</version>
<scope>compile</scope>
</dependency>