/** * Copyright 2017 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for t`he specific language governing permissions and * limitations under the License. */ 'use strict'; const functions = require('firebase-functions'); const gcs = require('@google-cloud/storage')(); const path = require('path'); const os = require('os'); const fs = require('fs'); const ffmpeg = require('fluent-ffmpeg'); const ffmpeg_static = require('ffmpeg-static'); /** * When an audio is uploaded in the Storage bucket We generate a mono channel audio automatically using * node-fluent-ffmpeg. */ exports.generateMonoAudio = functions.storage.object().onChange(event => { const object = event.data; // The Storage object. const fileBucket = object.bucket; // The Storage bucket that contains the file. const filePath = object.name; // File path in the bucket. const contentType = object.contentType; // File content type. const resourceState = object.resourceState; // The resourceState is 'exists' or 'not_exists' (for file/folder deletions). const metageneration = object.metageneration; // Number of times metadata has been generated. New objects have a value of 1. // Exit if this is triggered on a file that is not an audio. if (!contentType.startsWith('audio/')) { console.log('This is not an audio.'); return; } // Get the file name. const fileName = path.basename(filePath); // Exit if the audio is already converted. if (fileName.endsWith('_output.flac')) { console.log('Already a converted audio.'); return; } // Exit if this is a move or deletion event. if (resourceState === 'not_exists') { console.log('This is a deletion event.'); return; } // Exit if file exists but is not new and is only being triggered // because of a metadata change. if (resourceState === 'exists' && metageneration > 1) { console.log('This is a metadata change event.'); return; } // Download file from bucket. const bucket = gcs.bucket(fileBucket); const tempFilePath = path.join(os.tmpdir(), fileName); // We add a '_output.flac' suffix to target audio file name. That's where we'll upload the converted audio. const targetTempFileName = fileName.replace(/\.[^/.]+$/, "") + '_output.flac'; const targetTempFilePath = path.join(os.tmpdir(), targetTempFileName); const targetStorageFilePath = path.join(path.dirname(filePath), targetTempFileName); return bucket.file(filePath).download({ destination: tempFilePath }).then(() => { console.log('Audio downloaded locally to', tempFilePath); // Convert the audio to mono channel using FFMPEG. const command = ffmpeg(tempFilePath) .setFfmpegPath(ffmpeg_static.path) .audioChannels(1) .audioFrequency(16000) .format('flac') .on('error', (err) => { console.log('An error occurred: ' + err.message); }) .on('end', () => { console.log('Output audio created at', targetTempFilePath); // Uploading the audio. return bucket.upload(targetTempFilePath, {destination: targetStorageFilePath}).then(() => { console.log('Output audio uploaded to', targetStorageFilePath); // Once the audio has been uploaded delete the local file to free up disk space. fs.unlinkSync(tempFilePath); fs.unlinkSync(targetTempFilePath); console.log('Temporary files removed.', targetTempFilePath); }); }) .save(targetTempFilePath); }); });
https://github.com/firebase/functions-samples/blob/master/ffmpeg-convert-audio/functions/index.js
Существует еще один вариант, который я не видел здесь и который не включает «сложные» объекты или коллекции.
String[] array1 = new String[]{"one", "two"};
String[] array2 = new String[]{"three"};
String[] array = new String[array1.length + array2.length];
System.arraycopy(array1, 0, array, 0, array1.length);
System.arraycopy(array2, 0, array, array1.length, array2.length);
Я сделал этот код! Это работает как прелесть!
public String[] AddToStringArray(String[] oldArray, String newString)
{
String[] newArray = Arrays.copyOf(oldArray, oldArray.length+1);
newArray[oldArray.length] = newString;
return newArray;
}
Надеюсь, вам понравится !!
Если вы действительно хотите изменить размер массива, вы можете сделать что-то вроде этого:
String[] arr = {"a", "b", "c"};
System.out.println(Arrays.toString(arr));
// Output is: [a, b, c]
arr = Arrays.copyOf(arr, 10); // new size will be 10 elements
arr[3] = "d";
arr[4] = "e";
arr[5] = "f";
System.out.println(Arrays.toString(arr));
// Output is: [a, b, c, d, e, f, null, null, null, null]
String[] source = new String[] { "a", "b", "c", "d" };
String[] destination = new String[source.length + 2];
destination[0] = "/bin/sh";
destination[1] = "-c";
System.arraycopy(source, 0, destination, 2, source.length);
for (String parts : destination) {
System.out.println(parts);
}
Вы можете просто сделать это:
System.arraycopy(initialArray, 0, newArray, 0, initialArray.length);
Размер массива нельзя изменить. Если вам нужно использовать массив, вы можете использовать System.arraycopy (src, srcpos, dest, destpos, length);
Я не настолько разбираюсь в Java, но мне всегда говорили, что массивы - это статические структуры, которые имеют предопределенный размер. Вы должны использовать ArrayList или вектор или любую другую динамическую структуру.
Вам нужно использовать список коллекций. Вы не можете изменять размер массива.
Используйте List<String>
, например ArrayList<String>
. Это динамически растёт, в отличие от массивов (см. Эффективное Java 2nd Edition, пункт 25: Предпочтительные списки для массивов ).
import java.util.*;
//....
List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
System.out.println(list); // prints "[1, 2, 3]"
Если вы настаиваете на использовании массивов, вы можете использовать java.util.Arrays.copyOf
, чтобы выделить больший массив для размещения дополнительного элемента. Это действительно не лучшее решение.
static <T> T[] append(T[] arr, T element) {
final int N = arr.length;
arr = Arrays.copyOf(arr, N + 1);
arr[N] = element;
return arr;
}
String[] arr = { "1", "2", "3" };
System.out.println(Arrays.toString(arr)); // prints "[1, 2, 3]"
arr = append(arr, "4");
System.out.println(Arrays.toString(arr)); // prints "[1, 2, 3, 4]"
Это O(N)
за append
. ArrayList
, с другой стороны, имеет O(1)
амортизированную стоимость за операцию.
ArrayList
делает внутренне.
– Siyuan Ren
24 January 2014 в 09:55
вы можете создать arraylist и использовать Collection.addAll()
для преобразования строкового массива в ваш arraylist
Если вы хотите сохранить свои данные в простом массиве, например
String[] where = new String[10];
, и вы хотите добавить к нему некоторые элементы, как номера, пожалуйста, StringBuilder, который намного эффективнее, чем конкатенация строки.
StringBuilder phoneNumber = new StringBuilder();
phoneNumber.append("1");
phoneNumber.append("2");
where[0] = phoneNumber.toString();
Это гораздо лучший способ построить вашу строку и сохранить ее в вашем массиве «где».
На массивах нет метода append()
. Вместо этого, как уже было сказано, объект List может обслуживать необходимость динамической вставки элементов, например.
List<String> where = new ArrayList<String>();
where.add(ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1");
where.add(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1");
Или если вы действительно хотите использовать массив:
String[] where = new String[]{
ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1",
ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1"
};
, но затем это фиксированный размер, и никакие элементы не могут быть добавлены.
Как сказал тангенс, размер массива фиксирован. Но сначала вам нужно создать экземпляр, иначе это будет только нулевая ссылка.
String[] where = new String[10];
Этот массив может содержать только 10 элементов. Таким образом, вы можете добавить значение всего 10 раз. В вашем коде вы получаете нулевую ссылку. Вот почему он не работает. Чтобы иметь динамически растущую коллекцию, используйте ArrayList.
Добавление новых элементов в массив String.
String[] myArray = new String[] {"x", "y"};
// Convert array to list
List<String> listFromArray = Arrays.asList(myArray);
// Create new list, because, List to Array always returns a fixed-size list backed by the specified array.
List<String> tempList = new ArrayList<String>(listFromArray);
tempList.add("z");
//Convert list back to array
String[] tempArray = new String[tempList.size()];
myArray = tempList.toArray(tempArray);
<code>
, и это имело проблемы с родовыми типами. Пожалуйста, постарайтесь избежать этого тега, так как ... у него есть проблемы и отступы ваш код с 4 пробелами, чтобы получить правильное форматирование. Я сделал это для вашего вопроса :).
– Tom
11 December 2015 в 18:09
Apache Commons Lang имеет
T[] t = ArrayUtils.add( initialArray, newitem );
, он возвращает новый массив, но если вы по-настоящему работаете с массивами по какой-то причине, это может быть идеальным способом для этого.